简体   繁体   中英

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
  - 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 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 .

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 import module
module.foo()

A third less elegant way (but exactly the same as the above) is:

import modules.module as module
module.foo()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM