full closures

Andrae Muys amuys at shortech.com.au
Thu Feb 28 00:47:49 CET 2002


"Emile van Sebille" <emile at fenx.com> wrote in message news:<a5jbra$7ok00$1 at ID-11957.news.dfncis.de>...
> "Michael P. Soulier" <msoulier at nortelnetworks.com_.nospam> wrote in
> message news:slrna7q9m0.4pb.msoulier at pmerd071.ca.nortel.com...
> >     Hello.
> >
> >     While I know about bound methods in Python, I'm wondering if a
>  full
> > closure can be implemented. Can it?
> >
> >     Example: I want to pass an arbitrary code reference into a closure
>  and
> > have all of its variables preserved.
> >
> >     ie.
> >
> >     print "the current count is %d" % counter; counter += 1
> >
> >     Can I pass the above code into a closure, and then simply call it
> > repeatedly and see counter increment itself? If I pass in a function
>  with a
> > local variable, that local will be reset each time, and I don't want
>  to use a
> > global.
> >
> 
> I don't understand closures, but I might try something like:
> 
> class Counter:
>     def __init__(self):
>         self.count = 0
>     def __int__(self):
>         self.count += 1
>         return self.count
> 
> counter = Counter()
> print "the current count is %d" % counter
> 

That works, as does using a generator:

def Counter():
    counter = 0
    while 1:
        print "the current count is %d % counter
        counter += 1
        yield counter - 1   # might as well return it :)

counter = Counter()
counter.next()
 - the current counter is 0
 - 0
counter.next()
 - the current counter is 1
 - 1

Andrae



More information about the Python-list mailing list