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
- modules \
- __init__.py
- module.py
What I find weird is that I can’t import module.py with a simple import modules.module, because when I then try to call the function module.foo() in main.py it returns NameError: name 'module' is not defined. However, when I do import modules.module as module, everything works fine, the same with from modules import module. And when module.py is located in the same directory as main.py, a simple import module is completely sufficient for calling module.foo().
Now the question is, why is that? Why isn’t a simple import statement enough for importing a module from a package instead of the directory the script is in? Or am I doing something else wrong? An answer would be really appreciated since I am rather confused right now…
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 isfoo, andbaris 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
moduleinstead ofmodules.module, either doimport modules.module as module, as you found, or dofrom modules import module.