[Python-Dev] Re: PEP309 re-written

David Abrahams dave at boost-consulting.com
Mon Apr 5 09:55:38 EDT 2004


Peter Harris <scav at blueyonder.co.uk> writes:

> David Abrams wrote:
>
>>> If anyone can think of any really elegant hacks that are naturally
>>> expressed by partial function application I'd like to see them
>>  
>>
>>
>>There are millions, but AFAICT they're all more natural with lambda,
>>so...
>>
>>        "I agree that lambda is usually good enough, just not
>>        always."
>>
>>Examples, please?
>>  
>>
> Well, you can use partial to special-case classes as shorthand object
> factories.  So:
>
> C = partial(Canvas,my_window,width=100,height=100,bg='white')
>
> ...gives you a callable C that is a factory for Tkinter Canvases
> parented to my_window,
> 100 pixels on a side, and with a white background.  How this differs
> from lambda is that
> you can override keyword parameters from the supplied defaults:
>
> c1 = C()
>
> c2 = C(width=200)
>
> c3 = C(bg='red')

C = lambda *args, **kw: \
        Canvas(my_window, width=100, height=100, bg='white', *args, **kw)

OK, partial is a little shorter in that case.  I'm not sure that
example justifies a PEP, though.

    def _merge(d1, d2):
        d1.update(d2)
        return d1

    def partial(f, *args, **kw):
         return lambda *args2, **kw2: f(args + args2, merge(kw2,kw))

??

>>        "And I want the possibility of useful introspection and
>>        subclassing"
>>
>>Can you elaborate on that, please?
>>
>>  
>>
> You could maybe sub-class partial to override __call__ , in case you
> want to do anything fancy like pre-supplying arguments at arbitrary
> positions.

A *perfect* example of what lambda is already good at.

-- 
Dave Abrahams
Boost Consulting
www.boost-consulting.com




More information about the Python-Dev mailing list