PEP 260: simplify xrange()

Tim Peters tim_one at email.msn.com
Fri Jun 29 14:38:12 EDT 2001


[Chris Lawrence]
> You can try this code at the beginning of your program:
>
> import sys
> try:
>   if sys.hexversion < 0x10502f0: # 1.5.2 final
>     print 'Get a new version of Python!'
> except AttributeError:
>   print 'Get a new version of Python!'
>
> Dunno when sys.hexversion showed up, hence the try clause.

You can make it a little simpler by combining those tests via 3-argument
getattr:

import sys
if getattr(sys, "hexversion", 0) < 0x10502f0: # 1.5.2 final
    print "Get a new version of Python!"

> With more recent versions, you could also play with sys.version_info.

Same kind of trick applies, of course.  The *problem* is that if you're
relying on, for example, new syntax, you'll never execute this code under an
older version of Python:  Python compiles the entire module to bytecode
before executing any of it, and if an old version thinks there's a syntax
error during compilation, boom.

Rather than play with version numbers, it's usually better to use exec or
eval in a try/except block to determine *directly* whether the feature you
need is there.  In the case of new syntax, the outcome can be used to import
either a "new style" or "old style" version of a module, thus sidestepping
the "old version can't even compile some new forms of code" gotcha.





More information about the Python-list mailing list