python - Must I always reference a variable as global in my function if I were to use it? -
firstly, it's related function:
a = 3 def b(): = a+1 return
returns error.
isn't when local environment of b
couldn't find 'a'
, goes parent environment b
defined, is, 'a'
found 3
?
why must reference global a
in order work? meaning, have when immediate parent environment global environment? because below function seems able reference parent environment:
def b(): def c(): print c return c()
this such common issue is in python faq:
[...] when make assignment variable in scope, variable becomes local scope , shadows named variable in outer scope. since last statement in foo assigns new value x, compiler recognizes local variable.
so, python sees you're assigning local variable a = ..
, thinks, hey, local variable, i'm fine this. but, when bumps content of assignment (a + 1
) , sees same name a
complains because you're trying reference before assigning it.
this why following doesn't raise error:
def b(): = 20 = + 2 return
you first make assignment, a
treated local function b
, when a = + 2
encountered, python knows a
local variable, no confusion present here.
in other case added:
def b(): def c(): print c return c()
you referencing name enclosed in scope of function b
, referencing. if changed similar assignment before, you'll same unboundlocalerror
:
def b(): def c(): c = c + 20 return c()
Comments
Post a Comment