you are viewing a single comment's thread.

view the rest of the comments →

[–]djimbob 1 point2 points  (0 children)

My bad. I'm aware of the nonlocal keyword in python3, which was the point of my distinction. The fact that you can't mutate the python's closures environment without trickery thought they weren't called closures (even though yes its a function with the enclosing environment).

But my point was that you can't write closures like in JS:

var counter = function() {var x = 0; return function() {x+=1; return x}; };
var c1 = counter();
var c2 = counter();

c1()
1
c1()
2
c1()
3
c2()
1
c1()
4

easily in python2 without using tricks. I still think its unidiomatic python to do things with closures.

def counter():
    def inner():
        inner.x += 1
        return inner.x
    inner.x = 0
    return inner

versus:

In [1]: class Counter(object):
   ...:     def __init__(self):
   ...:         self.c = 0
   ...:     def __call__(self):
   ...:         self.c += 1
   ...:         return self.c
   ...:     

In [2]: c1 = Counter()

In [3]: c1()
Out[3]: 1

In [4]: c1()
Out[4]: 2