[Python-ideas] Syntactic sugar to declare partial functions

Robert Vanden Eynde robertve92 at gmail.com
Sat Aug 11 08:59:35 EDT 2018


Therefore one can do a decorator that gives .partial:

def partialize(f):
    from functools import partial
    f.partial = lambda *a, **b: partial(f, *a, **b)
    return f

@partialize
def f(x,y):
    return x-y

g = f.partial(5)
g(3)

That's the same idea as funcoperators.partially but doesn't return a new
function (which has the advantage of keeping help(f))

Le sam. 11 août 2018 à 14:53, Robert Vanden Eynde <robertve92 at gmail.com> a
écrit :

>
>
> Le sam. 11 août 2018 à 10:34, Vincent Maillol <vincent.maillol at gmail.com>
> a écrit :
>
>> Hello,
>>
>> Currently the user defined functions are mutables, there can be existed
>> python codes like this:
>>
>> >>> def foo():
>> ...     pass
>> ...
>> >>> if not hasattr(foo, 'partial'):
>> ...     foo.partial = {}
>> ...
>>
>> Adding a new method to function object can break existing projects, but
>> it is without impact with buit-in functions because they are immutables.
>>
>>
> Or use a decorator like in the lib ?
>
> from funcoperators import partially
>
> @partially
> def f(x, y):
>     return x-y
>
> g = f.part(4)
> g(5)
>
> The mutability solution however cannot have a "self" argument :
>
> def f(x,y):
>     return x-y
>
> f.stuff = lambda self: self(5, 2)
> f.stuff()  # missing self
>
> One would have to give "f".
>
> f.partial = lambda *a, **b: functools.partial(f, *a, **b)
>
> g = f.partial(4)
> g(5)
>
>
>> 2018-08-09 18:59 GMT+02:00 Michel Desmoulin <desmoulinmichel at gmail.com>:
>>
>>> I'd rather have functools.partial() to be added as a new method on
>>> function objects.
>>>
>>> >
>>> > fromfunctools importpartial
>>> >
>>> >
>>> > def add(x:int,y:int)->int:
>>> >     returnx +y
>>> >
>>> >
>>> > add_2 = partial(add,2)
>>> >
>>>
>>> Would become:
>>>
>>> add_2 = add.partial(2)
>>>
>>> Nothing to change on the parser, no obscure syntax for future readers,
>>> and we can get the opportunity of rewriting partial() in C as right now
>>> it is amazingly way, way slower than a lambda.
>>> _______________________________________________
>>> Python-ideas mailing list
>>> Python-ideas at python.org
>>> https://mail.python.org/mailman/listinfo/python-ideas
>>> Code of Conduct: http://python.org/psf/codeofconduct/
>>>
>>
>> _______________________________________________
>> Python-ideas mailing list
>> Python-ideas at python.org
>> https://mail.python.org/mailman/listinfo/python-ideas
>> Code of Conduct: http://python.org/psf/codeofconduct/
>>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180811/11b99dee/attachment.html>


More information about the Python-ideas mailing list