Python, doing conditional imports the right way

我怕爱的太早我们不能终老 提交于 2019-12-19 06:05:51

问题


Right now I have a class called A.

I have some code like this..

from my.package.location.A import A

...


foo = A.doSomething(bar)

This is great.

But now I have a new version of A called A, but in a different package, but I only want to use this other A in a certain 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)

This works fine. But it is ugly. How can I do this 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 a way I can do that easier? Without the factory layer? This now can turn every static method call on my class into 2 lines. I can always hold a reference in a class to reduce the impact, but im really hoping python has a simpler solution.


回答1:


Put your lines into 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 will get the proper A.




回答2:


You could 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 simply import AlwaysRightA as A and you're set.




回答3:


Could you just make a package in some third location that checks OldVersion and gets it's own A from the right place, then always import that package?




回答4:


from my.package.location.A import A as old
from new.package.location.A import A as new 

somthing like that?

old.someFunc()
new.someFunc()

i did't get the point of the question.



来源:https://stackoverflow.com/questions/6793748/python-doing-conditional-imports-the-right-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!