How to import classes defined in __init__.py
'
lib/
's parent directory must be insys.path
.Your '
lib/__init__.py
' might look like this:from . import settings # or just 'import settings' on old Python versionsclass Helper(object): pass
Then the following example should work:
from lib.settings import Valuesfrom lib import Helper
Answer to the edited version of the question:
__init__.py
defines how your package looks from outside. If you need to use Helper
in settings.py
then define Helper
in a different file e.g., 'lib/helper.py
'.
.| `-- import_submodule.py `-- lib |-- __init__.py |-- foo | |-- __init__.py | `-- someobject.py |-- helper.py `-- settings.py2 directories, 6 files
The command:
$ python import_submodule.py
Output:
settingshelperHelper in lib.settingssomeobjectHelper in lib.foo.someobject# ./import_submodule.pyimport fnmatch, osfrom lib.settings import Valuesfrom lib import Helperprintfor root, dirs, files in os.walk('.'): for f in fnmatch.filter(files, '*.py'): print "# %s/%s" % (os.path.basename(root), f) print open(os.path.join(root, f)).read() print# lib/helper.pyprint 'helper'class Helper(object): def __init__(self, module_name): print "Helper in", module_name# lib/settings.pyprint "settings"import helperclass Values(object): passhelper.Helper(__name__)# lib/__init__.py#from __future__ import absolute_importimport settings, foo.someobject, helperHelper = helper.Helper# foo/someobject.pyprint "someobject"from .. import helperhelper.Helper(__name__)# foo/__init__.pyimport someobject
If lib/__init__.py
defines the Helper class then in settings.py you can use:
from . import Helper
This works because . is the current directory, and acts as a synonym for the lib package from the point of view of the settings module. Note that it is not necessary to export Helper via __all__
.
(Confirmed with python 2.7.10, running on Windows.)
You just put them in __init__.py.
So with test/classes.py being:
class A(object): passclass B(object): pass
... and test/__init__.py being:
from classes import *class Helper(object): pass
You can import test and have access to A, B and Helper
>>> import test>>> test.A<class 'test.classes.A'>>>> test.B<class 'test.classes.B'>>>> test.Helper<class 'test.Helper'>