Scoping Issues

MRAB python at mrabarnett.plus.com
Thu May 24 21:51:58 EDT 2012


On 25/05/2012 02:23, SherjilOzair wrote:
> def adder():
> 	s = 0
> 	def a(x):
> 	    s += x
> 	    return sum
> 	return a
>
> pos, neg = adder(), adder()
> for i in range(10):
> 	print pos(i), neg(-2*i)
>
> This should work, right? Why does it not?
>
> Checkout slide no. 37 of a Tour of Go to know inspiration. Just wanted
> to see if python was the same as Go in this regard. Sorry, if I'm being
> rude, or anything.

If you bind to a name (assign to a variable) in a function, that name
is by default local to the function unless it's declared as "global" 
(which means "in this module's namespace") or "nonlocal" (which means
"in the enclosing function's namespace") (Python 3 only).



More information about the Python-list mailing list