Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python variable resolving

Tags:

python

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?

like image 443
Ish Avatar asked Aug 19 '10 20:08

Ish


People also ask

What is LEGB rule in Python?

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.

What is name resolution in Python?

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.

What is scope resolution in Python?

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.


1 Answers

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.

like image 103
Mark Byers Avatar answered Oct 19 '22 14:10

Mark Byers