• Posts
  • RSS
  • ◂◂RSS
  • Contact

  • Scope and Ambiguous Assignments In Python

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

    Fireside Friday, November 27, 2020

    Hey folks! Fireside this week. A bit of a change-up in terms of the coming attractions. I had planned to start “Textiles, How Did They Make It?” next, but I want to do a bit more reading on some of the initial stages of textile production (that is, the pr…

    via A Collection of Unmitigated Pedantry November 27, 2020

    Building Depth and Window Space

    How much window space does an apartment need, relative to its area, and how does this affect building style? A fascinating post from about a year ago on Urban Kchoze makes the argument that modern North American buildings are too deep – Simon calls them o…

    via Pedestrian Observations November 27, 2020

    Thoughts you mightn't have thunk about remote meetings

    Welcome to this week's edition of "building a startup in 2020," in which all your meetings are suddenly remote, and you probably weren't prepared for it. I know I wasn't. We started a "fully remote" company back in 2019, but …

    via apenwarr November 23, 2020

    more     (via openring)


  • Posts
  • RSS
  • ◂◂RSS
  • Contact