full closures

Emile van Sebille emile at fenx.com
Wed Feb 27 14:20:12 EST 2002


"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

Hopefully, someone will post something pythonish illustrating closures.
Maybe this time I'll get it.  ;-)

HTH,

--

Emile van Sebille
emile at fenx.com

---------




More information about the Python-list mailing list