HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonModerate

"import translate" in a way that works with Python 2 and 3

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
withwaytranslateworksthatpythonandimport

Problem

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?

Solution

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.

Code Snippets

from __future__ import absolute_import
from .core import translate

Context

StackExchange Code Review Q#141810, answer score: 10

Revisions (0)

No revisions yet.