[Prev][Next][Index][Thread]

Re: Closures



Bruce Hoult wrote:

> In article <3b770c44@pfaff.ethz.ch>, "Samuele Pedroni"
> <pedroni@inf.ethz.ch> wrote:
>
> > [Eric Kidd]
> > >
> > > Urgh.  So Python's closures are still broken:
> > There is simply another idiomatic way to get the same:
> >
> > class counter:
> >   def __init__(self):
> >      self.n = 0
> >   def __call__(self):
> >      self.n = self.n + 1
> >      return self.n
> >
> > c=counter()
> > print c()
> > print c()
>
> That's not a "closure", it's an "object".  They can be used for many fo
> the same things, but they are different.
>
> -- Bruce

Yes, perfecly aware of that (BTW I have implemented Python closures for
Jython).
My point was simply to show that Python can live with is choice of
different (broken?)
closures.

I know that in Perl for example closures are also used to construct
objects with (very strict) encapsulation,
but encapsulation was never a goal of Python OO design. Sometimes this can
hurt.

Python have both first-class closures and callable instances, it has been
decided not to change
the rules for local variable (which are really a matter of taste) and not
to fully exploit the
redundance of expressiveness that closures with rebinding would have
offered, OTOH with do
not copy binding, we share them:

def f(x):
   def g(): return x
   x *= 2
   return g

print f(2)() # print 4 not 2

regards, Samuele Pedroni.




Follow-Ups: References: