Python code for 2.5 and 2.4?

Robert Kern robert.kern at gmail.com
Mon Feb 25 16:02:50 EST 2008


Joseph Turian wrote:
> I was given code that was written for python 2.5, and uses simple
> functions like 'all' which are not present in 2.4
> 
> I want to make the code 2.4 compatible. What is the best way to do
> this?

If it's a single file, put something like the following code near the top. If 
you have multiple modules, put it into a separate module, say compatibility.py, 
and change the other modules to import these functions from there.


import sys
if sys.version_info[:2] < (2,5):
     def all(*args):
         ...
     def any(*args):
         ...
else:
     # Only bother with this else clause and the __all__ line if you are putting
     # this in a separate file.
     import __builtin__
     all = __builtin__.all
     any = __builtin__.any

__all__ = ['all', 'any']


> If I define function 'all', then won't I break 2.5 compatability?

No. Defining a function named the same thing as a builtin function will not 
break anything. You just wouldn't be using the efficient implementation already 
in Python 2.5. Using the if: else: suite above lets you have both at the expense 
of some clunkiness.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list