python - Why does printing a variable in global scope work, but modifying it does not? -
x = 1 def fn(): print x fn()
this prints "1":
x = 1 def fn(): x += 1 print x fn()
this raises "unboundlocalerror: local variable 'x' referenced before assignment"
what going on here?
in python, assigning variable implicit local declaration, resolved during bytecode compilation. so
x += 1
will create local variable x
, compile byte code:
0 load_fast 0 (x) 3 load_const 1 (1) 6 inplace_add 7 store_fast 0 (x)
the command load_fast
try load local variable x
not yet defined, that's why fails.
however, if define x
global
explicitly, use load_global
/store_global
instead.
in case of print
in first function, compiler assumes since no local variable declared (assigned) ever in function body, should mean global variable.
Comments
Post a Comment