proc A def/calls proc B: variable scoping rules.
NevilleDNZ
nevillednz at gmail.com
Wed Aug 16 00:36:43 EDT 2006
Steven D'Aprano wrote:
> Basically, when you access a variable name on the left hand side of an
> assignment (e.g. "a = 1") ANYWHERE in a function, that name is local to
> that function UNLESS it has been declared global.
ThanX Steven, I am still getting used to python scoping rules. I didn't
realise that using a variable on the left affected the variables on the
right. I WAS trying to avoid making the variable GLOBAL, and just pick
it out of the superior proc's scope.
>
> When you access a variable name as the right hand side of an assignment,
> or as an expression (e.g. "print a"), Python searches for it following the
> scoping rules: first it searches for it in the function's local variables,
> then the local variables of the next higher scope, and so on, and finally
> it searches for it amongst the globals (which is the top-level scope of
> everything).
I am more used to nested scopes, as in pascal/C.
>
> Play around with the code and see if it makes sense.
I will certainly dabble with your example further.
Many ThanX
NevilleD
BTW: here is my poor attempt at porting the "man boy test" algorithum
to python. As you can see in python I am still a boy... :-)
$ cat ./man_boy_test.py
#!/usr/bin/env python
def A(k, x1, x2, x3, x4, x5):
A.k=k
def B():
A.k = A.k - 1
B.out=A.out=A(A.k, B, x1, x2, x3, x4)
return B.out
if A.k <= 0: A.out = x4() + x5()
else: B()
return A.out
if A(10,lambda:1,lambda:-1,lambda:-1,lambda:1,lambda:0)==-67:
print "man"
else:
print "boy"
# end man_boy_test.py
$ ./man_boy_test.py
boy
More information about the Python-list
mailing list