Scoping Issues
Chris Rebert
clp2 at rebertia.com
Thu May 24 21:56:53 EDT 2012
On Thu, May 24, 2012 at 6:23 PM, SherjilOzair <sherjilozair at gmail.com> wrote:
> def adder():
> s = 0
> def a(x):
Add a "nonlocal s" declaration right here.
See http://www.python.org/dev/peps/pep-3104/
> 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?
Python doesn't have a C-like variable declaration scheme. So without a
`global` or `nonlocal` declaration, you can only assign to names which
reside in the innermost scope.
> Checkout slide no. 37 of a Tour of Go to know inspiration.
You mean slide #38 ("And functions are full closures.").
> Just wanted to see if python was the same as Go in this regard. Sorry, if I'm being rude, or anything.
I would suggest reading through the Python Language Reference
(http://docs.python.org/release/3.1.5/reference/index.html ) prior to
asking further questions, as it may well answer them for you.
Cheers,
Chris
More information about the Python-list
mailing list