简体   繁体   中英

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.

Most common case is that you have one major class that you want to provide to the users, call it MyCode .

Your package would be named mycode and you would put the body of MyCode class into 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.

Use absolute imports, it'll work fine across python versions. Inside mycode/__init__.py put:

from __future__ import absolute_import

from mycode.mycode import MyClass

where the __future__ import works from Python 2.5 and onwards; see PEP 328 . Without the absolute_import import, import mycode is ambiguous; 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.

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

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