Question

I have a Python package with several modules.

What I can do:

It's possible to use all modules from the package in my program by modifying __init__.py of the package, by importing all modules in it:

#__init__.py
import module1
import module2

Then I simply import package in my program and can access classes/functions in all the modules by their full name

#My program
import package
a = package.module1.A()

QUESTION:

Is there any way to automate addition of imports to __init__.py so I don't need to specify them manually?

Was it helpful?

Solution

This is another answer that might be closer to what you want.

In __init__.py you can add this to import all python files in the package.

Note that it doesn't do packages.. not sure how. And I'm using windows

from os import listdir
from os.path import abspath, dirname, isfile, join
# get location of __init__.py
init_path = abspath(__file__)
# get folder name of __init__.py
init_dir = dirname(init_path)
# get all python files
py_files = [file_name.replace(".py", "") for file_name in listdir(init_dir) \
           if isfile(join(init_dir, file_name)) and ".py" in file_name and not ".pyc" in file_name]
# remove this __init__ file from the list
py_files.remove("__init__")

__all__ = py_files

OTHER TIPS

The init file doesn't work like that.. I think you're thinking of something like this..

if you have the file structure:

my_program.py
/my_package
    __init__.py
    module1.py
    module2.py

in __init__.py you can write this line to edit the way import * works for my_package

__all__ = ["module1", "module2"]

now in my_program.py you can do this:

from my_package import *
a = module1.A()

Hope that helps! You can read more here: https://docs.python.org/2/tutorial/modules.html#importing-from-a-package

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top