variable scope question?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • globalrev

    variable scope question?



    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()
  • Gary Herron

    #2
    Re: variable scope question?

    globalrev wrote:

    >
    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()
    --

    >
    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
    UnboundLocalErr or: 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

    Comment

    Working...