Given following code:
def A() :
b = 1
def B() :
# I can access 'b' from here.
print( b )
# But can i modify 'b' here? 'global' and assignment will not work.
B()
A()
For the code in B()
function variable b
is in outer scope, but not in global scope. Is it possible to modify b
variable from within B()
function? Surely I can read it from here and print()
, but how to modify it?
For anyone looking at this much later on a safer but heavier workaround is. Without a need to pass variables as parameters.
I don't know if there is an attribute of a function that gives the
__dict__
of the outer space of the function when this outer space isn't the global space == the module, which is the case when the function is a nested function, in Python 3.But in Python 2, as far as I know, there isn't such an attribute.
So the only possibilities to do what you want is:
1) using a mutable object, as said by others
2)
result
.
Nota
The solution of Cédric Julien has a drawback:
result
The global b after execution of
A()
has been modified and it may be not whished soThat's the case only if there is an object with identifier b in the global namespace
You can, but you'll have to use the global statment (not a really good solution as always when using global variables, but it works):