Variables in Python can be used before they are set. This will create a runtime error, not a syntax error. Here is an example of using local variables:
>>> def f(): ... return a ... a = 3 ... >>> f() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in f UnboundLocalError: local variable 'a' referenced before assignment
This is in contrast to languages that consider dereferencing an unassigned or undefined variable of syntax error. Python does not “capture” the current state of the lexical region; it simply uses references to mutable lexical regions. Here is a demo:
>>> def f(): return a ... >>> f() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 1, in f NameError: global name 'a' is not defined >>> a = 3 >>> f() 3
source share