PEP 309 - Built-in closure type (with tentative syntax proposal)

Alexander Schmolck a.schmolck at gmx.net
Mon Feb 10 17:10:53 EST 2003


Googling for "curry" might be a good idea...

Peter Harris <scav at blueyonder.co.uk> writes:
> Hi all.
> 
> Slightly regretting submitting this PEP in the middle of an
> if-then-else expression jihad, but maybe anyone who is bored
> with the rhetoric would like something else to argue about.
> 
> My proposal is for a built-in closure type for Python, and
> a syntax for closure literals.
> 
> The reference implementation for the easy part is just:
> 
> class closure(object):
>      __slots__=('fn','args','kw')
>      def __init__(self, fn, *args, **kw):
>          self.fn, self.args, self.kw = (fn, args, kw)
> 
>      def __call__(self, *args, **kw):
>          d = self.kw.copy()
>          d.update(kw)
>          return self.fn(*(self.args + args), **d)
> 
> So you can freeze a function or other callable with a partial
> argument list and keyword arguments into a handy callable
> object.
> 
> Obviously, the C implementation would try to minimise the
> penalty of a dict copy and update per call, if there's a
> nifty way to do it. If not, it's still a powerful abstraction
> that would be useful even if it's not particularly fast.
> 
> The kind of things where I see myself using it is in UI callbacks,
> which never get executed in a tight loop anyway (unless something
> is already wrong).
> 
> I give a few examples in the PEP. Here are a couple more:
> 
>      clamp = closure(max,0) # so clamp(3)==3, clamp(-1)==0 etc.
> 
>      # button factory specialised to white buttons in my_window
>      buttonmaker=closure(Tkinter.Button, my_window, bg='white')
> 
> 
> The syntax proposal is more controversial. I want a function
> call operator @(*args,**kw) that instead of invoking __call__ on its
> left argument, returns a closure object.
> 
> So the above examples would be written:
> clamp=max@(0)
> buttonmaker=Tkinter.Button@(my_window,bg='white')
> 
> I'm a great fan of concise syntax, and this really appeals to me,
> but what is the community view? Does python need a closure type?
> Is the @ syntax too ugly to be worth it?
> 
> Peter Harris
> 
> 

-- 
Alexander Schmolck     Postgraduate Research Student
                       Department of Computer Science
                       University of Exeter
A.Schmolck at gmx.net     http://www.dcs.ex.ac.uk/people/aschmolc/




More information about the Python-list mailing list