Modules that provide differing functionality amongst different Python versions...

holger krekel pyth at devel.trillke.net
Sun Apr 21 11:43:08 EDT 2002


On Sun, Apr 21, 2002 at 07:29:08AM -0700, Allan Crooks wrote:
> Hi,
> 
> I was wondering what the best approach is on providing libraries for
> varying versions of Python?
>  (...)
> 
> ---------------
> 
> <2.0 code>
> if sys.version[:2] < (2, 1): return
> 
> <2.1 code>
> if sys.version[:2] < (2, 2): return
> 
> <2.2 code>
> 
> ---------------
> 
> But that wouldn't work, because earlier versions of Python would still
> report SyntaxErrors, as it would have a problem with iterator
> statements.

there might a very interesting way to do it:

#include the next function into your module
def forversion(minversionstr, execstring):
	""" simple check if version is ok ... """
        from sys import version
        from string import split,find
        sysversion=split(version[:find(version,' ')],'.')
        minversion=split(minversionstr,'.')

        return sysversion < minversion and '' or execstring


# and this is what you can do inside your module 

exec forversion("2.2",
"""
#special hottest code for 2.2
from __future__ import generators

def fantastic_generator(str,step=2):
    for i in xrange(0,len(str),step):
        yield int(str[i:i+step])

class a:
    def forward(self,str):
        for obj in fantastic_generator(str):
            yield obj

""")

exec forversion("2.2",
"""
for obj in fantastic_generator('052342'):
        print "fantastic generator provides:",obj

for obj in a().forward('663311'):
    print 'forwarder yields', obj
""")

welcome to python's powerful execution facilities :-)
If you call this with python 2.1, 2.0 it does nothing 
(same for 1.5, i hope). 

Defining 'version-dependent' methods of objects with this
idiom basically works, too. Onyl __future__ makes
some problems. The problem here is that

  exec "from __future__ import generators"
  def f():
    yield 1

does not seem to work completly as expected. so you can't easily 
use generators in several 'forversion' places. Just use them 
at the beginning.

Everything else than __future__ should be ok, though!

regards,

	holger





More information about the Python-list mailing list