Others have suggested assigning to locals()
. This won't work inside a function, where locals are accessed using the LOAD_FAST
opcode, unless you have an exec
statement somewhere in the function. To support this statement, which could create new variables that are not known at compile time, Python is then forced to access local variables by name within the function, so writing to locals()
works. The exec
can be out of the code path that is executed.
def func(varname):
locals()[varname] = 42
return answer # only works if we passed in "answer" for varname
exec "" # never executed
func("answer")
>>> 42
Note: This only works in Python 2.x. They did away with this foolishness in Python 3, and other implementations (Jython, IronPython, etc.) may not support it either.
This is a bad idea, though. How will you access the variables if you don't know their name? By locals()[xxx]
probably. So why not just use your own dictionary rather than polluting locals()
(and taking the chance of overwriting a variable your function actually needs)?