So I am trying to import a module “foo” that contains directories “bar” and “wiz”. “bar” contains python files a.py, b.py, and c.py. “wiz” contains python files x.py, y.py and z.py.
$ ls foo
__init__.py bar wiz
$ ls foo/bar
__init__.py a.py b.py c.py
$ ls foo/wiz
__init__.py x.py y.py z.py
In the python shell (more precisely, the django manage.py shell), I type the following and see the following results:
>>> import foo
>>> dir(foo.bar)
['__builtins__', '__doc__', '__file__', '__name__', '__path__', 'a']
>>> dir(foo.wiz)
['__builtins__', '__doc__', '__file__', '__name__', '__path__', 'x', 'y']
>>> foo.wiz.x
<module 'foo.wiz.x' from '/dir/'>
>>> foo.wiz.z
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'module' object has no attribute 'z'
Why are only certain modules being imported here? Why can’t I get access to z, or to b or c for that matter? I thought everything would be imported and accessible based solely on the directory that contained them. Also, if the import is failing, it is failing silently.
Does anyone know what is going on here?
When importing
foo, Python will just loadfoo/__init__.py, it will not (automatically) loadfoo.barorfoo.wiz. Therefore, trying to access those without explicitely importing them will raise aAttributeError.If some module imports sub-modules like
foo.barorfoo.bar.a, Python will load the respective files and create a reference to themoduleobject withinfoo. So it is possible that some modules are available without explicit import.If you want
foo.barto always export its submodulesa,bandc, you can import those from withinfoo/bar/__init__.py. Then, these modules will be availabe wheneverfoo.baris imported.