I want to import a particular and unusual module. In order to import this module, I must prepare the environment for its import, import the module, and then change the environment again following its import. The way I can do this is as follows:
argv_tmp = sys.argv
sys.argv = []
from ROOT import *
sys.argv = argv_tmp
I want to abstract the procedures surrounding the actual import into two functions resulting in main code of the following form:
pre_ROOT_import()
from ROOT import *
post_ROOT_import()
How can these functions -- functions that take no arguments and return no values -- perform these procedures?
A context manager works well here. It holds sys.argv locally and restores it even if an exception is raised in ROOT.
import contextlib
@contextlib.contextmanager
def argv_tmp():
tmp = sys.argv
sys.argv = []
try:
yield
finally:
sys.argv = tmp
with argv_tmp():
from ROOT import *