Hacker Read top | best | new | newcomments | leaders | about | bookmarklet login

Yes, I just meant to point out that there is a way to do closures in Python 2.x. Looks like here the author wants a function that saves its internal state, i.e., a generator.


view as:

Closures actually do work without that trick since many versions back. It's setting a nonlocal that still sucks.

Well, they sort of work. Closures don't work properly [0] in some lexical contexts without using the default-argument trick because of the way function definition works in Python:

    fs = []
    for i in range(5):
      def f():
        print(i)
      fs.append(f)

    gs = []
    for i in range(5):
      def g(i=i):
        print(i)
      gs.append(g)
The functions in `fs` all print 4 because they all refer to the final object assigned to `i` in the `for` loop. The functions in `gs`, on the other hand, print 0 through 4, as they "should" because the `i` in `g` is assigned to the object currently referenced by the `for` loop's `i` each time the `def` statement is evaluated. This distinction in behavior is obscured in the classic function-inside-a-function example of closures because you pass the object to be closed over to the outer function each time you want to create a new closure. So the result is analogous to using the default-argument trick in the example above.

Anyway, that's all I meant to point out. I misinterpreted your reference to `nonlocal`, which I'm not very familiar with as I don't really use Python 3 much yet. So sorry for my nonsensical reply.

[0] By "properly" I mean as closures work in pure functional languages, where they originated. I realize a programmer who understands Python's data model shouldn't generally expect them to work that way in Python.


Oh, yes, good point, though I wouldn't call it a problem with how closures work -- Lisp has the same issue, for example, if you did a (dolist) or (loop) just like your Python code's 'for' loop. In both cases we have a language not originally designed for a style using frequent closures and running into some gotchas thereby.

My answers above were really short because I was on a tablet. May have come across as curt.


Legal | privacy