Given the following code:
a = 0
def foo():
# global a
a += 1
foo()
When run, Python complains: UnboundLocalError: local variable 'a' referenced before assignment
However, when it's a dictionary...
a = {}
def foo():
a['bar'] = 0
foo()
The thing runs just fine...
Anyone know why we can reference a in the 2nd chunk of code, but not the 1st?
The LEGB rule is a kind of name lookup procedure, which determines the order in which Python looks up names. For example, if you reference a given name, then Python will look that name up sequentially in the local, enclosing, global, and built-in scope. If the name exists, then you'll get the first occurrence of it.
Python's name resolution is sometimes called the LGB rule, after the scope names: When you use an unqualified name inside a function, Python searches three scopes—the local (L), then the global (G), and then the built-in (B)—and stops at the first place the name is found.
Scope resolution is required when a variable is used to determine where should its value be come from. Scope resolution in Python follows the LEGB rule. L, Local — Names assigned in any way within a function (or lambda), and not declared global in that function.
The difference is that in the first example you are assigning to a
which creates a new local name a
that hides the global a
.
In the second example you are not making an assignment to a
so the global a
is used.
This is covered in the documentation.
A special quirk of Python is that – if no global statement is in effect – assignments to names always go into the innermost scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With