proc A def/calls proc B: variable scoping rules.
NevilleDNZ
nevillednz at gmail.com
Tue Aug 15 21:38:49 EDT 2006
Steve Holden wrote:
> Hardly surprising. This statement is an assignment to x2, which
> therefore becomes local to the function. Since no previous value has
> been assigned to this local, the exception occurs.
But: In this case the assignment is never reached.... eg..
#!/usr/bin/env python
def A():
print "begin A:"
x1=123
x2=456
def B():
print "begin B:",x1,x2
if False: x2 = x2 + 210 # Magically disappears when this line is
commented out.
print "end B:",x1,x2
print "pre B:",x1,x2
B()
print "end A:",x1,x2
A()
# same error message...
$ ./x1x2.py
begin A:
Pre B: 123 456
begin B: 123
Traceback (most recent call last):
File "./x1x2.py", line 13, in <module>
A()
File "./x1x2.py", line 11, in A
B()
File "./x1x2.py", line 7, in B
print "begin B:",x1,x2
UnboundLocalError: local variable 'x2' referenced before assignment
I guess it is something to do with the scoping of duck typing.
I WAS expecting that the A.x2 was visable until x2 is somehow (by
assignment) made local. I guess I am learning that what you do to a
variable in the middle of scope (even in an unreachable statement)
effects the entire scope. Is there anyway to force x2 to be A.x2
(without declaring it to be a global.x2)? Maybe I can put it into a
A.local class...
The result sh/could be:
begin A:
pre B: 123 456
begin B: 123 456
end B: 123 666
end A: 123 666
ThanX
NevilleD
More information about the Python-list
mailing list