• Posts
  • RSS
  • ◂◂RSS
  • Contact

  • 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:

    A Big Problem With The Going To Bed Book

    One day my dad was reading this book called the "Going to Bed Book" to my sister Nora. The book is basically about a bunch of animals who are getting ready for bed on a boat. They go down the stairs, take a bath, hang their towels on the wall, find…

    via Lily Wise's Blog Posts September 18, 2023

    Investing in boundaries with young kids

    Putting in some work to get the behavior you want The post Investing in boundaries with young kids appeared first on Otherwise.

    via Otherwise August 15, 2023

    Self-driving car bets

    This month I lost a bunch of bets. Back in early 2016 I bet at even odds that self-driving ride sharing would be available in 10 US cities by July 2023. Then I made similar bets a dozen times because everyone disagreed with me. The first deployment to pot…

    via The sideways view July 29, 2023

    more     (via openring)


  • Posts
  • RSS
  • ◂◂RSS
  • Contact