I have a function P(). A call to load_variables() should give P the variable x.
load_variablesshould be able to accept defaults as keyword arguments.
How can this be done?
I have tried the following:
import inspect
def P():
x = 1
load_variables(x = 2)
return x
def load_variables(**kargs):
stack = inspect.stack()
try:
locals_ = stack[1][0].f_locals
finally:
del stack
for __k, __v in kargs.iteritems():
locals_[__k] = __v
print P() # => should print 2
The x = 1 line shouldn’t actually be there, as I want load_variables() to just bleed the x into P‘s scope.
Is there another, perhaps better, way to do this? What I want is:
- Variables have a default value, e.g.
x = 2in the above call toload_variables(). - I can overwrite these in
load_variables, for instance,load_varibales()has access to a dictionary of variables, and ifxis already here, we overwrite it, and spill thisxinstead of the one given as default argument.
The Python compiler and bytecode interpreter handles, where possible, references to local variables as slots into a defined-size array. This means that if a local variable is not initialised (assigned to) in a scope then the language will not know that a slot for the variable exists in the scope, and will instead look for the variable in an enclosing scope or the global scope. Looking at a disassembly of the function
P:You can see that without an assignment to
xin local scopePwill look for it in global scope.The right way to do this is to explicitly state which variables you expect the
load_variablesfunction to return, using unpacking: