5

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?

Bach
  • 6,145
  • 7
  • 36
  • 61
Konstantin
  • 2,937
  • 10
  • 41
  • 58

2 Answers2

3

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

flakes
  • 21,558
  • 8
  • 41
  • 88
  • The way I described works indeed. The method you described should work fine too. However, it's again manually adding all the modules into package. – Konstantin Apr 15 '14 at 18:50
  • @Konstantin I meant the "automate addition of imports" part. Unless you want to use the `os` module to walk through the package directory and add all the found py files to the `__all__` list. – flakes Apr 15 '14 at 18:53
  • Can I do it in a way PyDev or any other IDE still handles autocompletion? – Konstantin Apr 15 '14 at 18:56
  • @Konstantin Not sure about the IDE side of things. I do all my writing in notepad++ so I'm not much help in that regard :p – flakes Apr 15 '14 at 18:58
  • I upvoted your reply, but still believe that someone may already solve the issue and may help me) – Konstantin Apr 15 '14 at 18:59
  • @Konstantin No worries, Mate! – flakes Apr 15 '14 at 19:00
3

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
flakes
  • 21,558
  • 8
  • 41
  • 88