Python global closure scoping oddity
Beware closuring in global variables.
world = 'Endor'
def world_name():
def world_knower():
print(world)
world = 'Hoth'
return world_knower
knower = world_name()
knower()
# Hoth
In the above example, the reference the local world
was closured in to world_knower
, and the value was changed after the world_knower
declaration.
What if we use the global
keyword to let python know we want to use the global version of this variable?
world = 'Endor'
def world_name():
global world
def world_knower():
print(world)
world = 'Hoth'
return world_knower
knower = world_name()
knower()
# Hoth
Yikes, the inner function still uses the outer functions local reference. I guess if we truly want to ignore the local reference, we need to declare that world
is global in the inner function.
world = 'Endor'
def world_name():
def world_knower():
global world
print(world)
world = 'Hoth'
return world_knower
knower = world_name()
knower()
# Endor
Tweet