How to get/set local variables of a function (from outside) in Python?
Solution 1:
No. A function that isn't being run doesn't have locals; it's just a function. Asking how to modify a function's locals when it's not running is like asking how to modify a program's heap when it's not running.
You can modify constants, though, if you really want to.
def func():
a = 10
print a
co = func.func_code
modified_consts = list(co.co_consts)
for idx, val in enumerate(modified_consts):
if modified_consts[idx] == 10: modified_consts[idx] = 15
modified_consts = tuple(modified_consts)
import types
modified_code = types.CodeType(co.co_argcount, co.co_nlocals, co.co_stacksize, co.co_flags, co.co_code, modified_consts, co.co_names, co.co_varnames, co.co_filename, co.co_name, co.co_firstlineno, co.co_lnotab)
modified_func = types.FunctionType(modified_code, func.func_globals)
# 15:
modified_func()
It's a hack, because there's no way to know which constant in co.co_consts is which; this uses a sentinel value to figure it out. Depending on whether you can constrain your use cases enough, that might be enough.
Solution 2:
I'm not sure what your use-case is, but this may work better as a class. You can define the __call__
method to make a class behave like a function.
e.g.:
>>> class sample_func(object):
... def __init__(self):
... self.a = 78
... self.b = range(5)
... def __call__(self):
... print self.a, self.b, self.x
...
>>> f = sample_func()
>>> print f.a
78
>>> f.x = 3
>>> f()
78 [0, 1, 2, 3, 4] 3
(this is based on your toy example, so the code doesn't make much sense. If you give more details, we may be able to provide better advice)