I am interacting with a python 2.x API written in a non-OO way, it uses module-global scope for some internal state driven stuff. It\'s needed in a context where it\'s no longer
Just remove the module from sys.modules:
>>> import sys
>>> import mod as m1
>>> m1.x = 1
>>> del sys.modules['mod']
>>> import mod as m2
>>> m2.x = 2
>>> m1.x
1
You can try by fooling sys.modules
import badmodule as badmod1
import sys
del sys.modules['badmodule']
import badmodule as badmod2
If this works or not of course depends on what the bad module is doing...
This can be achieved by importing the module via different paths. That is - if in your sys.path you have two different dotted routes to the module, the module cache will create two different instances of the module with different symbol trees, globals and so on.
This can be used to have multiple versions of a library also.
Beware that it will lead to exceptions not being caught (as you are trying to catch the wrong symbol).
Easiest way is to make two copies of the module and import them separately. For example, take your module thingabobber
and make two copies named thingabobber1
and thingabobber2
. Then just:
import thingabobber1, thingabobber2
If this isn't feasible, delete the module from sys.modules
after initially importing it so you get a second copy on the second import.
import sys
import thingabobber as thingabobber1
del sys.modules["thingabobber"]
import thingabobber as thingabobber2
I haven't used it personally but it seems that Exocet library may help.