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

    More on the Deutschlandtakt

    The Deutschlandtakt plans are out now. They cover investment through 2040, but even beforehand, there’s a plan for something like a national integrated timetable by 2030, with trains connecting the major cities every 30 minutes rather than hourly. But the…

    via Pedestrian Observations July 1, 2020

    How do cars fare in crash tests they're not specifically optimized for?

    Any time you have a benchmark that gets taken seriously, some people will start gaming the benchmark. Some famous examples in computing are the CPU benchmark specfp and video game benchmarks. With specfp, Sun managed to increase its score on 179.art (a su…

    via Posts on Dan Luu June 30, 2020

    Quick note on the name of this blog

    When I was 21 a friend introduced me to a volume of poems by the 14th-century Persian poet Hafiz, translated by Daniel Ladinsky. I loved them, and eventually named this blog for one of my favorite ones. At some point I read more and found that Ladinsky’s …

    via The whole sky June 21, 2020

    more     (via openring)


  • Posts
  • RSS
  • ◂◂RSS
  • Contact