既然__init__.py是可选的,请更正导入和包的结构 [英] Correct import and package structure now that __init__.py is optional

查看:88
本文介绍了既然__init__.py是可选的,请更正导入和包的结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个包含要运行的脚本的软件包.它们将包含在子文件夹中的模块直接导入脚本.既然在Python 3.3之后不再需要 __init__,那么正确的文件结构和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> import <name>形式.否则将不会产生有效的名称.假设您通过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.pypython3 -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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆