[Python-ideas] Infix functions
Mathias Panzenböck
grosser.meister.morti at gmx.net
Sat Feb 22 03:34:58 CET 2014
Am 2014-02-22 03:16, schrieb Andrew Barnert:
> From: Mathias Panzenböck <grosser.meister.morti at gmx.net>
> Sent: Friday, February 21, 2014 5:45 PM
>
>
>> Am 2014-02-21 23:05, schrieb Andrew Barnert:
>>> While we're discussing crazy ideas inspired by a combination of a long-abandoned PEP and Haskell idioms (see the implicit lambda thread), here's another: arbitrary infix operators:
>>>
>>> a `foo` b == foo(a, b)
>>>
>>
>> If you really want to you could do this:
>
>
> This is basically the same trick you use in Haskell to allow arbitrary expressions rather than just identifiers to be used infix. Which I don't think you actually want to allow. Also, it requires you to declare certain functions as infix-able rather than just use any functions arbitrarily. Of course that does allow you to give the infix version a different name than the prefix version, like bar = infix(foo), or even bar = infix(partial(Spam(2).long_method_name, 'eggs')), which could I suppose be useful.
>
> One question about the implementation:
>
>> class infix2(object):
>> __slots__ = 'func', 'arg1'
>>
>> def __init__(self,func,arg1):
>> self.func = func
>> self.arg1 = arg1
>>
>> def __call__(*args,**kwargs):
>> self, args = args[0], args[1:]
>> return self.func(self.arg1,*args,**kwargs)
>
>
> First, why not just:
>
> def __call__(self, *args, **kwargs):
> return self.func(self.arg1, *args, **kwargs)
>
Because then you can never pass a keyword argument named "self". Exotic case, but still.
> More importantly, I assume this is to allow auto-partialing, so "spam" |foo is a normal function of one argument that you can pass around? That doesn't actually work the same way as Haskell operators, and it looks pretty weird in Python too, and I can't think of when you'd want it, but it is clever.
>
Yeah, I just thought maybe one would like to have that. No special thoughts there.
Also this is not my idea. I saw such code somewhere and wrote this down from memory. It could even be that I saw this on
this mailing list.
Btw. bugfix for the infix class:
class infix(object):
__slots__ = 'func',
def __init__(self,func):
self.func = func
def __ror__(self,arg1):
return infix2(self.func, arg1)
def __call__(*args,**kwargs):
self, args = args[0], args[1:]
return self.func(*args,**kwargs)
More information about the Python-ideas
mailing list