Correct import and package structure now that __in

2019-02-25 18:20发布

问题:

I'm building a package that contains scripts to be run. They import modules contained in a subfolder directly under the script. Now that __init__ is not required after Python 3.3, what's the correct file structure and import statement to have? I'd like to not have to specify the import from the topmost folder down, only as a relative path, here sub/module.

This is the current state of the file structure:

Root\
    src\
        sub\
            module.py
        script.py
        parent_module.py
    setup.py

# Inside script.py
import sub.module      # Doesn't work
from sub import module # Doesn't work
import src.sub.module  # Does work!

import .sub.module     # Doesn't work
import .parent_module  # Does work!

I imagine I need to have some __init__ file, but what and where would that be? Any help is greatly appreciated, I don't know much about packaging.

Also, I'm certainly open to suggestions to changing the structure, if that makes things easier.

回答1:

The missing __init__.py are not the problem - you are using outdated relative imports.

import sub.module         # implicit relative import - py2 only
from . import sub.module  # explicit relative import

Note that a . import always requires the from .<where> import <name> form. It would not produce a valid name otherwise. The following should work, assuming your run script.py via python3 -m src.script - an IDE will likely do the same.

from . import sub.module
from .sub import module
from .sub.module import *
from . import parent_module

If you are running as plain python3 script.py or python3 -m script, you cannot use relative imports. Only absolute imports will work in this case.

import sub.module
from sub import module
from sub.module import *
import parent_module

While you do not need __init__.py files, it is a good idea to add them if your package is not a namespace. Otherwise, other similarly constructed packages of the same name may be inserted into yours.