# coding: utf-8
def func():
print 'x is', x
#x = 2 #if I add this line, there will be an error, why?
print 'Changed local x to', x
x = 50
func()
print 'Value of x is', x
- I don’t add the
global xin func function, but it can still findxis 50, why? - When I add the
x=2line in the func function, there will be an error (UnboundLocalError: local variable 'x' referenced before assignment), why?
The trick here is that local names are detected statically:
xis not assigned in the function, references toxresolve to the the global scopexis assigned anywhere in the function, Python assumes thatxis thus a local name everywhere in the function. As a consequence, the first line becomes an error because local namexis used before being assigned.In other words: assigned name is treated as local everywhere in the function, not just after the point of assignment.