Import mechanism to support multiple Python versions

Serge Orlov Serge.Orlov at gmail.com
Fri Mar 18 14:59:50 EST 2005


Nicolas Fleury wrote:
> Hi,
> 	I'm trying to support two Python versions at the same time and I'm
> trying to find effective mechanisms to support modules compiled in
> C++ transparently.
>
> 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?:
>
> 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).

I used the following approach application-wide:
===== The very start of main file ===
resolve_package_dependencies()
import package

def main():
    ...

# boilerplate at the end of main file
def resolve_package_dependencies():
    if sys.version_info[0:2] == (2,5):
        import package1
        sys.modules["package"] = sys.modules["package1"]
    else:
        import package2
        sys.modules["package"] = sys.modules["package2"]

=====================================

I've never needed that for packages like you, but as far as I
remember package specific modules are stored like
"package.module" so aliasing "package45" with "package" in your
case will look like
sys.modules[__name__+".package"] = sys.modules[__name__+".package45"]

  Serge.




More information about the Python-list mailing list