proc A def/calls proc B: variable scoping rules.

Steve Holden steve at holdenweb.com
Tue Aug 15 20:50:05 EDT 2006


NevilleDNZ wrote:
> Can anyone explain why "begin B: 123" prints, but 456 doesn't?
> 
> $ /usr/bin/python2.3  x1x2.py
> begin A:
> Pre B: 123 456
> begin B: 123
> Traceback (most recent call last):
>   File "x1x2.py", line 13, in ?
>     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
> 
> 
> $ cat x1x2.py
> #!/usr/bin/env python
> def A():
>   print "begin A:"
>   x1=123;
>   x2=456;
>   def B():
>     print "begin B:",x1,x2
>     x2 = x2 - 1; # comment out this line and script x1x2 magically
> works!!

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.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd          http://www.holdenweb.com
Skype: holdenweb       http://holdenweb.blogspot.com
Recent Ramblings     http://del.icio.us/steve.holden




More information about the Python-list mailing list