Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
up vote 10 down vote accepted

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.

share|improve this answer
    
Not sure if the question does belong here but this answer definitly taught me something! Thanks :) – Josay yesterday
    
this will work for any python version >2.5? – mou yesterday
    
@mou no >=2.5, but you shouldn't be running Python2.5 – Joe Wallis yesterday
    
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. – user2357112 yesterday

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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