[英]How to deal with python imports so they work easily with py2 and py3?
I am looking for a way to write python packages and modules that makes them Python 3 friendly and also it makes easy to import them. 我正在寻找一种编写python软件包和模块的方法,使它们对Python 3友好,并且也易于导入它们。
Most common case is that you have one major class that you want to provide to the users, call it MyCode
. 最常见的情况是,您有一个要提供给用户的主要类,称为
MyCode
。
Your package would be named mycode
and you would put the body of MyCode class into mycode/mycode.py
. 您的程序包将命名为
mycode
,并将MyCode类的主体放入mycode/mycode.py
。
Now, you would expect that people could do one of these: 现在,您希望人们可以执行以下操作之一:
import mycode
obj = mycode.MyClass()
or: 要么:
from mycode import MyClass()
obj = MyClass()
Now, the question is what you should put inside the __init__.py
in order to make this work, in both python 2.6+ and 3.x. 现在,问题是在python 2.6+和3.x中都应该在
__init__.py
中放入什么才能使它起作用。
Use absolute imports, it'll work fine across python versions. 使用绝对导入,它将在python版本之间正常工作。 Inside
mycode/__init__.py
put: 在
mycode/__init__.py
内部放置:
from __future__ import absolute_import
from mycode.mycode import MyClass
where the __future__
import works from Python 2.5 and onwards; 从python 2.5及更高版本开始
__future__
导入的位置; see PEP 328 . 参见PEP 328 。 Without the
absolute_import
import, import mycode
is ambiguous; 如果没有
absolute_import
导入,则import mycode
模棱两可; Python 3 will treat it as absolute and load the top-level package, Python 2 treats it as relative and import the nested module instead. Python 3将其视为绝对,并加载顶级包,Python 2将其视为相对,然后导入嵌套模块。
The alternative is to use a relative import: 另一种方法是使用相对导入:
from .mycode import MyClass
which will work across the same spectrum of versions. 可以在相同的版本范围内使用。
from mycode import *
添加到mycode/__init__.py
将使mycode/mycode.py
的内容可从mycode
包中导入,就像它只是一个普通的模块(如mycode.py
)一样,与从中import mycode
时一样与mycode.py
脚本( /mycode/
)相同的目录,或相对导入mycode/mycode.py
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.