Python by doing conditional imports in the right way

I now have a class called A.

I have code like this.

from my.package.location.A import A ... foo = A.doSomething(bar) 

It's great.

But now I have a new version of A named A, but in a different package, but I want to use only this different A in a specific scenario. So I can do something like this:

 if(OldVersion): from my.package.location.A import A else: from new.package.location.A import A ... foo = A.doSomething(bar) 

It works great. But it is ugly. How can I do it better? I really want to do something like this

 from my.abstraction.layer.AFactory import AFactory ... myA = AFactory.giveMeA() # this looks at "OldVersion" and gives me the correct A foo = myA.doSomething(bar) 

Is there any way to make this easier? Without a factory layer? Now it can turn any call of a static method into my class in 2 lines. I can always hold the link in the class to reduce the impact, but I really hope that python will have a simpler solution.

+7
source share
4 answers

Put your lines in a_finder.py:

 if OldVersion: from my.package.location.A import A else: from new.package.location.A import A 

Then in your product code:

 from a_finder import A 

and you get the correct A.

+13
source

You can do something like this:

AlwaysRightA.py

 import sys if(OldVersion): from my.package.location.A import A else: from new.package.location.A import A sys.modules[__name__] = A 

Then just import AlwaysRightA as A and you install.

+2
source

Could you just make the package in some third place that checks OldVersion and gets its own A from the right place and then always imports the package?

+1
source
 from my.package.location.A import A as old from new.package.location.A import A as new 

Anything like that?

 old.someFunc() new.someFunc() 

I did not understand the question.

-2
source

All Articles