由于 __init__.py 是可选的,因此在包内导入 [英] Imports inside package now that __init__.py is optional
问题描述
我正在构建一个包含要运行的脚本的包.它们直接在脚本下导入子文件夹中包含的模块.既然 __init__
在 Python 3.3 之后不再需要,那么正确的文件结构和 是什么?import
语句有什么?我想不必指定从最顶层文件夹向下的导入,仅作为相对路径,这里是 sub/module
.
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!
我想我需要 some __init__
文件,但是那是什么?在哪里?非常感谢任何帮助,我对包装不太了解.
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.
推荐答案
缺少的 __init__.py
不是问题 - 您使用的是过时的相对导入.
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
请注意,.
导入始终需要 from .<where>导入
表单.否则它不会产生有效的名称.以下应该可以工作,假设您通过 python3 -m src.script
运行 script.py
- IDE 可能会这样做.
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
如果您以普通的 python3 script.py
或 python3 -m script
运行,则不能使用相对导入.在这种情况下,只有绝对导入才有效.
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
<小时>
虽然您不需要 __init__.py
文件,但如果您的包不是命名空间,最好添加它们.否则,其他类似构造的同名包可能会插入到您的包中.
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.
这篇关于由于 __init__.py 是可选的,因此在包内导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!