Real Closures in Python

by chromatic

I missed this trick a while back, but for everyone who has to program in Python and misses actual working closures, close over a container variable or use a function attribute. jjlinuxland's Modifying a Counter in a Closure and the comments explain more.

Now to play with lambda to see if this trick makes them more useful....


Jeremy Jones
2006-11-28 07:11:49
I'd really like to see an example of using closures for which there is not a better "Pythonic" alternative. The website you've given is using a list and an inner function to maintain some state for something calling the function. I think this particular case would be much better written using generators. For example

def counter(start):

"""Create a counter starting at ``start``."""

while 1:
start += 1
yield start

if __name__ == '__main__':
c = counter(5)
for i in range(3):

In this case, the generator maintains some state for the function. The difference is that the the "Modifying a Counter in a Closure" example returns a function which you call each time in the loop. My example returns a generator and you have to call its .next() method.

Again, I'd love to see an example of a closure which Python doesn't have a more elegant alternative for. I'm not dinging closures. Maybe I'm dinging Python's clunky implementation of closures. Doing closures in Python with functions (including lambdas) seems clunky compared to, say, blocks in Ruby. That's why I will almost always reach for generators or list comprehensions (or something simpler) to accomplish the same sort of task.

If someone wants to post an elegant closure in Python, I'd love to see it. (Not saying they don't exist. Just saying I'd love to see it).