• Posts
  • RSS
  • ◂◂RSS
  • Contact

  • Scope and Ambiguous Assignments In Python

    March 21st, 2011
    tech, python  [html]
    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:

    The Limit of Circles in the Suburbs

    In dense urban cores, it’s valuable to run circular rail lines. They connect dense near-center neighborhoods to one another without going through the more congested center, and help make transferring between parallel lines more efficient, again through av…

    via Pedestrian Observations September 6, 2020

    Collections: Bread, How Did They Make It? Addendum: Rice!

    As an addendum on to our four-part look at the general structures of the farming of cereal grains (I, II, III, IV) this post is going to briefly discuss some of the key ways that the structures of rice farming differ from the structures of wheat and barle…

    via A Collection of Unmitigated Pedantry September 4, 2020

    Notes on “Anthropology of Childhood” by David Lancy

    I read David Lancy’s “The Anthropology of Childhood: Cherubs, Chattel, and Changelings” and highlighted some passages. A lot of passages, it turns out. [content note: discussion of abortion and infanticide, including infanticide of children with disabilit…

    via The whole sky August 27, 2020

    more     (via openring)


  • Posts
  • RSS
  • ◂◂RSS
  • Contact