Let's say I have a scope with variables, and a function called in that scope wants to change some immutable variables:
def outer ():
s = 'qwerty'
n = 123
modify ()
def modify ():
s = 'abcd'
n = 456
Is it possible to somehow access the external area? Something like nonlocal variables from Py3k.
Of course, I can do s,n = modify(s,n) in this case, but what if I need some kind of general βinjectionβ that runs there, and should be able to reassign to arbitrary variables?
I have performance, so if possible, eval and checking the stack frame is not welcome :)
UPD : This is not possible. Period. However, there are several ways to access variables in the external area:
- Use global variables. By the way,
func.__globals__ is a mutable dictionary;) - Store variables in dict / class-instance / any other mutable container
- Give the variables as arguments and return them as a tuple:
a,b,c = innerfunc(a,b,c) - Enter another function bytecode. This is possible with the python
byteplay module.
kolypto
source share