4
\$\begingroup\$

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?

\$\endgroup\$

1 Answer 1

10
\$\begingroup\$

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

As documented in the __future__ module.

\$\endgroup\$
4
  • \$\begingroup\$ Not sure if the question does belong here but this answer definitly taught me something! Thanks :) \$\endgroup\$
    – SylvainD
    Sep 19, 2016 at 13:50
  • \$\begingroup\$ this will work for any python version >2.5? \$\endgroup\$
    – mou
    Sep 19, 2016 at 13:51
  • \$\begingroup\$ @mou no >=2.5, but you shouldn't be running Python2.5 \$\endgroup\$
    – Peilonrayz
    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 with from whatever.core import translate. The future statement just turns off implicit relative imports. \$\endgroup\$ Sep 19, 2016 at 23:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.