Import mechanism to support multiple Python versions

Nicolas Fleury nid_oizo at yahoo.com_remove_the_
Fri Mar 18 14:15:29 EST 2005


Nicolas Fleury wrote:
> import cppmymodule
> 
> would be equivalent to:
> 
> if sys.version == "2.4":
>     import cppmymodule24 as cppmymodule
> elif sys.version == "2.3":
>     import cppmymodule23 as cppmymodule
> 
> for all modules under the package and all modules with names beginning 
> with cpp (or another way to identify them).

Since all my imports are absolute, my code looks more like:

import root.subpackage.cppmymodule

So I guess, I can add this in root/__init__.py and everything would be fine:

def myimport(name, globals=None, locals=None, fromlist=None,
              __import__=__import__):
     names = name.split('.')
     if names[0] == 'root' and names[-1][0:3] == 'cpp':
         name += '%s%s' % sys.version_info[0:2]
     return __import__(name, globals, locals, fromlist)

__builtins__['__import__'] = myimport

It seems to work, is that right?

Thx and regards,
Nicolas



More information about the Python-list mailing list