\$\begingroup\$
\$\endgroup\$
I'm trying to make my script cross-Python (Python 2 and 3 compatible), and to solve an import problem I did this:
__init__.py
file
import sys
if (sys.version_info[0] < 3):
from core import translate
else:
from .core import translate
Is it the good way to do it?
200_success
146k22 gold badges190 silver badges479 bronze badges
1 Answer 1
\$\begingroup\$
\$\endgroup\$
4
No that's not the best way to import in both Python2 and Python3, if you have to support Python 2.5.0a1 and above. This is as you can use:
from __future__ import absolute_import
from .core import translate
answered Sep 19, 2016 at 13:47
-
\$\begingroup\$ Not sure if the question does belong here but this answer definitly taught me something! Thanks :) \$\endgroup\$SylvainD– SylvainD2016年09月19日 13:50:58 +00:00Commented Sep 19, 2016 at 13:50
-
\$\begingroup\$ this will work for any python version >2.5? \$\endgroup\$mou– mou2016年09月19日 13:51:21 +00:00Commented Sep 19, 2016 at 13:51
-
\$\begingroup\$ @mou no >=2.5, but you shouldn't be running Python2.5 \$\endgroup\$2016年09月19日 13:52:19 +00:00Commented Sep 19, 2016 at 13:52
-
\$\begingroup\$ You can also use explicit relative imports without
from __future__ import absolute_import
, or import the module by its fully-qualified name withfrom whatever.core import translate
. The future statement just turns off implicit relative imports. \$\endgroup\$user2357112– user23571122016年09月19日 23:53:32 +00:00Commented Sep 19, 2016 at 23:53
lang-py