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

Allan Crooks googlegroups at sixtyten.org
Mon Apr 22 10:55:01 EDT 2002


Carl Banks <imbosol at vt.edu> wrote in message news:<gs6v9a.vb1.ln at 127.0.0.1>...
> holger krekel wrote:
> > On Sun, Apr 21, 2002 at 02:12:16PM -0400, Carl Banks wrote:
> >> Allan Crooks wrote:
> >> > Hi,
> >> > 
> >> > I was wondering what the best approach is on providing libraries for
> >> > varying versions of Python?
> >> > (...)
>  
> >> # Import stuff for version 2.1
> >> if sys.version[:2] >= (2,1):
> >>     from mymodule2_1 import *
> >> 
> >> # Import for version 2.2
> >> if sys.version[:2] >= (2,2):
> >>     from mymodule2_2 import *
> > 
> > this solves part of the 'code duplication' problem. Might get a bit tricky
> > if you just want to define a few additional methods for some classes
> > (for example 'generator versions' of methods otherwise returning lists).
> 
> I wouldn't say so.  It is straightforward enough to add a method to a
> class any time:
> 
> >>> class a:
> ...    pass
> ...
> >>> def p(self,x):
> ...    print "hello, %s" % x
> ...
> >>> a.p = p
> >>> b = a()
> >>> b.p("world")
> hello, world

That would still be problematic, how would you refer to class "a" that
is defined in another module? Say you had the following code in
module_20:

class a:
    def hello(self): return 'hello there!'

And you had this code in module_22:

from module_20 import a
a.hello = lambda self: 'hello there again!'

If module_21 then defines it's own 'hack' of module_20's 'a', then
module_22 will lose the change, unless you are aware of the import in
module_21.

I know it's a reasonably simple change, but if you forget about it, it
could be a bit confusing. I think the best thing to do would be to
have the 'newer' module inheriting the entire namespace from the older
module.

So module_21 will have a "from module_20 import *" line, module_22
will have "from module_21 import *" and so on, with the frontend
module doing the correct import of whichever module corresponds to the
version of Python being used.

I'm also a bit reluctant of namespace hacking of classes, since it
just seems too... 'hacky'. It would also make inheritance a problem.

Maintaining concurrent versions doesn't seem as bad as I first
thought...

> I just did it how the OP did it, without bothering to check.  It
> should be sys.version_info[:2] >= (x,y)

Ooops, my mistake.

I like the ideas people come up with though...

Allan.



More information about the Python-list mailing list