Scope and Ambiguous Assignments In Python

March 21st, 2011
python, tech
Consider the following two Python snippets:
    name='Mary'
    def print_name():
      print name
    print_name()
    print name
  
    name='Mary'
    def print_name():
      name='John'
    print_name()
    print name
  
The first will print 'Mary', twice. The second will print 'Mary' once. This happens because while python interprets reads as looking outside the current scope, writes can't be [1] anything but local. So the assignment to 'name' inside 'print_name' creates a new variable that disappears when the function exits.

So now consider:

    name='Mary'
    def print_name():
      print name
      name='John'
    print_name()
    print name
  
This code will generate an error:
    Traceback (most recent call last):
      File "tmp.py", line 5, in <module>
        print_name()
      File "tmp.py", line 3, in print_name
        print name
    UnboundLocalError: local variable 'name' referenced before assignment
  
The error is because within a function a variable must be either local or global. If it's local, the 'print name' is illegal because 'name' isn't defined yet. If it's global, the 'name="John"' is illegal because you can't assign outside your scope. So python chooses "local" and decides that the 'print name' line is invalid.

[1] well, you could use the 'global' keyword

Comment via: r/Python

Recent posts on blogs I like:

Starting With Chords

A lot of people play fiddle. Basically nobody starts by learning chords before learning melodies. But that's actually how I learned. I started with chords. One of the nice things about learning to play violin this way is that you can go busking even…

via Anna Wise's Blog Posts November 15, 2024

Stuffies

I have some stuffies and I just have a bunny. Bunny is a rabbit. Woof is a seal. My favorite stuffie is bun bun. I play with my stuffies. Sometimes I jump up with them and I roll them. I can just throw them in the air when I want to play bthululubp wi…

via Nora Wise's Blog Posts November 15, 2024

You Can Buy A Malaria Net

2024 election takes

via Thing of Things November 6, 2024

more     (via openring)