In my working python directory I create:
packagename/__init__.py
packagename/modulename.py
test.py
In modulename.py I create some empty class:
class Someclass(object):
pass
in test.py:
import packagename
packagename.modulename.Someclass()
Why I can’t call packagename.modulename.someclass() in test.py ?
AttributeError: 'module' object has no attribute 'modulename'
I understand that the right way is:
import packagename.modulename
or
from packagename import modulename
But I do not understand why I get this error in my case.
Update:
In other words is there any way to import a package’s content with all modules in the distinct namespace?
I need correct pythonic expression for:
from packagename import * as mynamespace
If you had 100 modules in the “packagename” package, would you want them all to be imported automatically when you imported just the top-level name? That wouldn’t usually be a good idea, so Python doesn’t do it.
If you want to have that particular module imported automatically, just include it in the
__init__.pylike so:Alternatively, using Python 2.5 or 2.6:
(In later versions, you can ditch the
from __future__part.)Edit: there is no built-in mechanism to ask Python to import all possible submodules inside a package. That’s not a common use case, and it’s better handled explicitly by having your
__init__.pyimport precisely those things that you want. It would be possible to put something together to do the job (using__import__()and such) but it is better in most cases just to explicitly import all submodules as described.