variable scope question?

G

Gary Herron

globalrev said:
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()
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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top