patternpythonModerate
Import "izip" for different versions of Python
Viewed 0 times
izipdifferentforpythonversionsimport
Problem
A common idiom that I use for Python2-Python3 compatibility is:
However, a comment on one of my Stack Overflow answers implies that there may be a better way. Is there a more clean way to accomplish this?
try:
from itertools import izip
except ImportError: #python3.x
izip = zipHowever, a comment on one of my Stack Overflow answers implies that there may be a better way. Is there a more clean way to accomplish this?
Solution
Not sure this is really an answer, or I should elaborate on my comment, and in hindsight probably not even a very good comment anyway, but:
Firstly, you can just simplify it to:
What I was thinking about was:
From 2.6 you can use as per the docs:
You do however then have the same problem of
The advantage of using
Updated - also in the docs:
The 2to3 tool that ports Python 2 code to Python 3 will recognize this usage and leave the new builtins alone.
Firstly, you can just simplify it to:
try:
from itertools import izip as zip
except ImportError: # will be 3.x series
passWhat I was thinking about was:
From 2.6 you can use as per the docs:
from future_builtins import map # or zip or filterYou do however then have the same problem of
ImportError - so:try:
from future_builtins import zip
except ImportError: # not 2.6+ or is 3.x
try:
from itertools import izip as zip # < 2.5 or 3.x
except ImportError:
passThe advantage of using
future_builtin is that it's in effect a bit more "explicit" as to intended behaviour of the module, supported by the language syntax, and possibly recognised by tools. For instance, I'm not 100% sure, but believe that the 2to3 tool will re-write zip correctly as list(zip(... in this case, while a plain zip = izip may not be... But that's something that needs looking in to.Updated - also in the docs:
The 2to3 tool that ports Python 2 code to Python 3 will recognize this usage and leave the new builtins alone.
Code Snippets
try:
from itertools import izip as zip
except ImportError: # will be 3.x series
passfrom future_builtins import map # or zip or filtertry:
from future_builtins import zip
except ImportError: # not 2.6+ or is 3.x
try:
from itertools import izip as zip # < 2.5 or 3.x
except ImportError:
passContext
StackExchange Code Review Q#26271, answer score: 14
Revisions (0)
No revisions yet.