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:
func.__globals__
is a mutable dictionary ;)a,b,c = innerfunc(a,b,c)
byteplay
python module.Define the variables outside of the functions and use the global
keyword.
s, n = "", 0
def outer():
global n, s
n = 123
s = 'qwerty'
modify()
def modify():
global n, s
s = 'abcd'
n = 456
Sometimes I run across code like this. A nested function modifies a mutable object instead of assigning to a nonlocal
:
def outer():
s = [4]
def inner():
s[0] = 5
inner()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With