Overloading operators for currying, a PEP309 suggestion

Marco Barisione marco.bari at vene.ws
Thu Mar 13 05:47:43 EST 2003


On Tue, 11 Mar 2003 03:50:30 GMT, Lenard Lindstrom wrote:

> In PEP 309 a new operator, '@', was tentatively proposed for currying. But
> given that Python allows operator overloading, why not use some existing
> operators for currying 'function' objects? The 'function' class has few
> operations defined for it, so there remain many to choose from. Here are my
> suggestions:
> [...]

I would prefer using "%"; "function % something" should be equivalent 
to"curry(function) % something". This would be similar to string 
formatting.

class curry:
    def __init__(self, fun, *args, **kwargs):
        self.fun = fun
        self.pending = args[:]
        self.kwargs = kwargs.copy()
    def __call__(self, *args, **kwargs):
        if kwargs and self.kwargs:
            kw = self.kwargs.copy()
            kw.update(kwargs)
        else:
            kw = kwargs or self.kwargs
        return self.fun(*(self.pending + args), **kw)
    def __mod__(self, arg):
        kw = self.kwargs.copy()
        if isinstance(arg, (dict, UserDict.UserDict)):
            kw.update(arg)
            a = tuple(self.pending)
        else:
            a = tuple(self.pending) + tuple(arg)
        return curry(self.fun, *a, **kw)


>>> def foo(a, b, c): print a, b, c
.. 
>>> call1 = foo % (1, 2, 3)
>>> call1()
1 2 3
>>> 
>>> call2 = foo % {'a': 12, 'b': 123, 'c': 42}
>>> call2()
12 123 42
>>> 
>>> call3 = foo % (1, 2)
>>> call3(97)
1 2 97
>>> 
>>> call4 = foo % (1, 2) % {'c': 9}
>>> call4()
1 2 9



BTW: Why?
Is currying so widespread?
I love Python because of its clear syntax, why should we make it less 
clear?

I think the better solution is to add a "functional" module.

-- 
Marco Barisione
http://spazioinwind.libero.it/marcobari/




More information about the Python-list mailing list