Scoping Issues

Dave Angel d at davea.name
Thu May 24 21:59:50 EDT 2012


On 05/24/2012 09:23 PM, 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?
>

Guess that depends on what you mean by work.  First, it gets a syntax
error on the print function call, because you omitted the parens.  When
I fixed that, I got
   UnboundLocalError: local variable 's' referenced before assignment

so I fixed that, and got
     inconsistent use of tabs and spaces in indentation

because you mistakenly used tabs for indentation. Then I got the output
    <built-in function sum> <built-in function sum>

because sum is a built-in function.  Presumably you meant to return s,
not sum.

Here's what I end up with, and it seems to work fine in Python 3.2 on Linux:

def adder():
    s = 0
    def a(x):
        nonlocal s
        s += x
        return s
    return a

pos, neg = adder(), adder()
for i in range(10):
    print (pos(i), neg(-2*i))

.....
Output is:

0 0
1 -2
3 -6
6 -12
10 -20
15 -30
21 -42
28 -56
36 -72
45 -90


-- 

DaveA




More information about the Python-list mailing list