Closures

G

Gustavo Niemeyer

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()
 
M

Michele Simionato

Gustavo Niemeyer said:
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()


This is a nice hack! Why not to make it available as a Cookbook recipe?

Michele Simionato
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top