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?

200_success
146k22 gold badges190 silver badges479 bronze badges
asked Sep 19, 2016 at 13:30
\$\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.

answered Sep 19, 2016 at 13:47
\$\endgroup\$
4
  • \$\begingroup\$ Not sure if the question does belong here but this answer definitly taught me something! Thanks :) \$\endgroup\$ Commented Sep 19, 2016 at 13:50
  • \$\begingroup\$ this will work for any python version >2.5? \$\endgroup\$ Commented Sep 19, 2016 at 13:51
  • \$\begingroup\$ @mou no >=2.5, but you shouldn't be running Python2.5 \$\endgroup\$ Commented 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\$ Commented Sep 19, 2016 at 23:53

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.