Import mechanism to support multiple Python versions

Greg Ewing greg at cosc.canterbury.ac.nz
Sun Mar 20 21:21:38 EST 2005


Nicolas Fleury wrote:
> All my code in under a single package.  Is it possible to override the 
> import mechanism only for modules under that package and sub-packages so 
> that?:

Yes. A package module has a __path__ attribute to which
you can add additional directories to be searched for
submodules of that package. So in your package's
__init__.py you can do something like

   if sys.version == "2.4":
     subdir = "python24"
   elif sys.version == "2.3":
     subdir = "python23"

   __path__.append(os.path.join(os.path.basename(__file__, subdir)))

The directory structure is then

   yourpackage/
     __init__.py
     python23/
       cppmymodule.pyd   (2.3 version)
     python24/
       cppmymodule.pyd   (2.4 version)

but at run time it will appear as though one version or
the other of cppmymodule is a direct submodule of
yourpackage.

-- 
Greg Ewing, Computer Science Dept,
University of Canterbury,	
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg



More information about the Python-list mailing list