A package directly-imported doesn't automatically place subpackages or submodules into its namespace:
>>> import mydir
>>> dir(mydir)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']
(Notice that there is no innerdir
here.)
But if you import through a package, Python will connect the namespaces together:
>>> import mydir.innerdir
>>> dir(mydir)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', 'innerdir']
>>> dir(mydir.innerdir)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']
(Notice that there is no mymodule
in mydir.innerdir
.)
Python allows you to say explicitly what some submodules to include automatically in a package using the __all__
magic variable in the __init__.py
, but by default it will just run the code in __init__.py
code and not do anything else.
You can do any of the following:
import mydir.innerdir.mymodule; mydir.innerdir.mymodule.hi()
from mydir.innerdir import mymodule; mymodule.hi()
from mydir.innerdir.mymodule import hi; hi()
Alternatively, you can edit your __init__.py
files to include __all__
vars for wildcard importing.
# file mydir/innerdir/__init__.py
print 'Running mydir/innerdir/__init__.py'
__all__ = ['mymodule']
Then you can do stuff like this:
from mydir.innerdir import *; mymodule.hi()
Even crazier, you can eagerly import subpackages and modules (I don't recommend this!):
# file mydir/__init__.py
print 'Running mydir/__init__.py'
import innerdir
# file mydir/innerdir/__init__.py
print 'Running mydir/innerdir/__init__.py'
import mymodule
Now these will work:
import mydir; mydir.innerdir.mymodule.hi()
from mydir import innerdir; innerdir.mymodule.hi()
You might want to brush up on the documentation for packages, which explains all this and has a directory structure exactly like the one you show here.
from mydir import innerdir
now you don't have to use the whole path