Say, I have some scope with variables, and a function called in this scope wants to change some immutable variables:
def outer():
s = qwerty
n = 123
modify()
def modify():
s = abcd
n = 456
Is it possible somehow to access the outer scope? Something like nonlocal variables from Py3k.
Sure I can do s,n = modify(s,n) in this case, but what if I need some generic injection which executes there and must be able to reassign to arbitrary variables?
I have performance in mind, so, if possible, eval & stack frame inspection is not welcome :)
UPD : It s impossible. Period. However, there are some options how to access variables in the outer scope:
- Use globals. By the way, func.__globals__ is a mutable dictionary ;)
- Store variables in a dict/class-instance/any other mutable container
- Give variables as arguments & get them back as a tuple: a,b,c = innerfunc(a,b,c)
- Inject other function s bytecode. This is possible with byteplay python module.