Can't Import Python Module From A Subdirectory With A Simple Import Statement
So I want to import a module from a python package that is a subdirectory of the one where the main script is located. This is the directory structure: maindir \ - main.py - mo
Solution 1:
It does import the module, it just doesn't make its name directly accessible. When you do import foo.bar
, the name that is imported is foo
, and bar
is only accessible as an attribute of that. You use that form of import if that is what you want; that's what it's for. If you don't want that, use a different form of the import statement.
If you want to be able to type module
instead of modules.module
, either do import modules.module as module
, as you found, or do from modules import module
.
Solution 2:
When you import you still need to use the full package syntax to use the function foo.
The below should work
import modules.module
modules.module.foo()
A better way to do this is
from modules importmodulemodule.foo()
A third less elegant way (but exactly the same as the above) is:
import modules.module as modulemodule.foo()
Post a Comment for "Can't Import Python Module From A Subdirectory With A Simple Import Statement"