Excuse me for being new to python. I feel as if this should be possible, but I have looked all over in this site (among others). I can't seem to directly change a variable in a function with a nested function. I've tried
global
to no avail. I could reassign it to get around this but it causes issues later.
Example:
def Grrr():
a = 10
def nested(c):
b = 5
c -= b
nested(a)
return a
I am trying to stay away from
def Grrr():
a = 10
def nested(c):
b = 5
c -= b
a = nested(a)
return a
If that is truly the best way, then I'll use it I guess. I just figured there were people here far better than I.
1 Answer 1
You could avoid using an argument and instead use nonlocal:
def Grrr():
a = 10
def nested():
nonlocal a
b = 5
a -= b
nested()
return a
If you want to pass in a variable to change, though, it can't be done†; Python doesn't have references in the C++ sense.
† without some horrible hackery
4 Comments
[thing] and passing that around instead of thing (much like Python's closure implementation uses cell objects), or is there actually a way to figure out which variable an argument came from and mess with the stack to alter its contents?dict of that stack frame.ctypes code to get at it anyway, but there's some edge cases and lots depends on how Python was compiled.