variable scope question?

Discussion in 'Python' started by globalrev, May 13, 2008.

  1. globalrev

    globalrev Guest

    globalrev, May 13, 2008
    #1
    1. Advertising

  2. globalrev

    Gary Herron Guest

    globalrev wrote:
    > http://mail.python.org/pipermail/python-list/2003-October/233435.html
    >
    > why isnt it printing a in the second(second here, last one in OP)
    > example before complaining?
    >
    > def run():
    > a = 1
    > def run2(b):
    > a = b
    > print a
    > run2(2)
    > print a
    > run()
    >
    > def run():
    > a = 1
    > def run2(b):
    > print a
    > a = b
    > run2(2)
    > print a
    > run()
    > --
    > http://mail.python.org/mailman/listinfo/python-list
    >

    If you had told us what error you got, I would have answered you hours
    ago. But without that information I ignored you until is was
    convenient to run it myself. Now that I see no one has answered, and I
    have time to run your examples, I see the error produced is

    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "<stdin>", line 6, in run
    File "<stdin>", line 4, in run2
    UnboundLocalError: local variable 'a' referenced before assignment

    and its obvious what the problem is.

    In run2 (of the second example), The assignment to a in the line "a=b"
    implies that a *must* be a local variable. Python's scoping rules say
    that if "a" is a local variable anywhere in a function, it is a local
    variable for *all* uses in that function. Then it's clear that "print
    a" is trying to access the local variable before the assignment gives it
    a value.

    You were expecting that the "print a" pickups it the outer scope "a" and
    the assignment later creates a local scope "a", but Python explicitly
    refuses to do that.

    Gary Herron
     
    Gary Herron, May 13, 2008
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Paul Opal
    Replies:
    12
    Views:
    963
    Paul Opal
    Oct 11, 2004
  2. ann
    Replies:
    13
    Views:
    676
    Patricia Shanahan
    Sep 13, 2005
  3. Steven T. Hatton
    Replies:
    9
    Views:
    492
  4. David Filmer
    Replies:
    19
    Views:
    250
    Kevin Collins
    May 21, 2004
  5. Andrew Falanga
    Replies:
    2
    Views:
    202
    Andrew Falanga
    Nov 22, 2008
Loading...

Share This Page