This happens because method_1
gets its own local scope where it can declare variables. Python sees value = True
and thinks you're creating a new variable named value
, local to method_1
.
The reason Python does this is to avoid polluting the outer scope's locals with variables from an inner function. (You wouldn't want assignments in regular, module-level functions to result in global variables being created!)
If you don't assign to value
, then Python searches the outer scopes looking for the variable (so reading the variable works as expected, as demonstrated by your method_2
).
One way to get around this is by using a mutable object instead of assigment:
result = { 'value': False }
def method_1():
result['value'] = True
In Python 3, the nonlocal
statement (see also docs) was added for exactly this scenario:
def method_1():
nonlocal value
value = True # Works as expected -- assigns to `value` from outer scope