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

Steve Holden steve at holdenweb.com
Tue Aug 15 22:42:11 EDT 2006


NevilleDNZ wrote:
> I inserted x1,x2 into A to force a wider scope and it works.
> 
> #!/usr/bin/env python
> def A():
>   print "begin A:"
>   A.x1=123;
>   A.x2=456;
>   def B():
>     print "begin B:",A.x1,A.x2
>     A.x2 = A.x2 + 210; # problem gone.
>     print "end B:",A.x1,A.x2
>   print "pre B:",A.x1,A.x2
>   B()
>   print "end A:",A.x1,A.x2
> A()
> 
> $ ./z1z2.py
> begin A:
> pre B: 123 456
> begin B: 123 456
> end B: 123 666
> end A: 123 666
> 
> $ python -V
> Python 2.5b3
> 
> I checked: This method even handles recursion giving a new instance of
> A.x2 each call.
> Is this the official way to scope/inherit scopes in sub procs?
> 
No. It's too horrible to contemplate without getting mild feelings of 
nausea. What exactly is it you are tring to achieve here (since I assume 
your goal wasn't to make me feel sick :-)?

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