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

NevilleDNZ nevillednz at gmail.com
Tue Aug 15 22:31:38 EDT 2006


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?

ThanX
NevilleD




More information about the Python-list mailing list