Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get 2 isolated instances of a python module

Tags:

python

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 singleton, and modifying the original code (not ours) is not an option.

Short of using subprocess runs of separate interpreters, is there any way I could box off the modules and interact with multiple instances of the module (thus treating it as an object)?

I need to use the module to drive 2 different setups - which it doesn't internally seem to work with.

Disclaimer: Please don't do this. Please do this only if in a very odd situation - and try to alter the situation in other ways before doing this. I did this to cope with odd code that could not be changed at the time of asking - not to provide a way to proliferate more odd code.

like image 709
Danny Staple Avatar asked Aug 08 '11 16:08

Danny Staple


1 Answers

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
like image 108
phihag Avatar answered Sep 21 '22 11:09

phihag