Closures

Gustavo Niemeyer niemeyer at conectiva.com
Thu Apr 29 17:04:02 EDT 2004


> Would you trade the "mutable integer" and "count(n=[0])" kludges for a
> solution like &count ?  Does anyone agree with me that a "closure
> variable prefix" is more explicit and readable?

import sys

class Closure:
    def __init__(self):
        self.__dict__ = sys._getframe().f_back.f_locals

def getFunc():
    counter = 0
    c = Closure()
    def count():
        c.counter += 1
        print c.counter
    return count

c = getFunc()
c()
c()
c()

-- 
Gustavo Niemeyer
http://niemeyer.net




More information about the Python-list mailing list