I have the following standard import procedure:
from ROOT import *
Because of the way ROOT handles command line options and arguments, something like the following is required in order to avoid screwing up the script's command line parsing:
argv_tmp = sys.argv
sys.argv = []
from ROOT import *
sys.argv = argv_tmp
I need to perform this operation in many scripts. This operation may change or there might turn out to be a better approach, so I want to centralise this procedure in a single function provided by some imported module, making it easy to change the procedure in future.
def import_ROOT():
# magic
import os
import sys
import_ROOT()
import docopt
How can I import the ROOT module from within a function such that the result of the script's operation is the same as for the from ROOT import *
procedure described above?
Due to how local variables are implemented in python you cannot do this. And since you don't know all the variables that may be imported you can't declare them global.
As to why you can't import unknown locals in a function. This is because at compile time python establishes all the different possible locals that may exist (anything that is directly assigned to and hasn't been declared global or nonlocal). Space for these locals are made in an array associated with each call of the function. All locals are then referenced by their index in the array rather than their name. Thus, the interpreter is unable to make additional space for unknown locals nor know how to refer to them at runtime.