[Python-ideas] sys.py3k
Steven D'Aprano
steve at pearwood.info
Sun Nov 4 23:33:42 CET 2012
On 05/11/12 08:49, anatoly techtonik wrote:
> if sys.py3k:
> # some py2k specific code
> pass
Do you expect every single Python 3.x version will have exactly the same
feature set? That's not true now, and it won't be true in the future.
In my option, a better approach is more verbose and a little more work, but
safer and more reliable: check for the actual feature you care about, not
some version number. E.g. I do things like this:
# Bring back reload in Python 3.
try:
reload
except NameError:
from imp import reload
Now your code is future-proofed: if Python 3.5 moves reload back into
the builtins, your code won't needlessly replace it. Or if you're running
under some environment that monkey-patches the builtins (I don't know,
IDLE or IPython or something?) you will use their patched reload instead
of the one in the imp module.
Or I go the other way:
try:
any
except NameError:
# Python 2.4 compatibility.
def any(items):
for item in items:
if item:
return True
return False
Now if I'm running under a version of 2.4 that has backported the
"any" function, I will prefer the backported version to my own.
--
Steven
More information about the Python-ideas
mailing list