[Python-ideas] Method chaining notation

Ron Adam ron3200 at gmail.com
Sun Feb 23 19:24:32 CET 2014



On 02/22/2014 08:48 PM, Chris Angelico wrote:
> On Sun, Feb 23, 2014 at 1:25 PM, Nick Coghlan<ncoghlan at gmail.com>  wrote:
>> >it's a fundamentally bad idea to blur that distinction: you should be
>> >able to tell*at a glance*  whether an operation is mutating an
>> >existing object or creating a new one...
>> >
>> >Compare:
>> >
>> >     seq = get_data()
>> >     seq.sort()
>> >
>> >     seq = sorted(get_data())
>> >
>> >Now, compare that with the proposed syntax as applied to the first operation:
>> >
>> >     seq = []->extend(get_data())->sort()
>> >
>> >That*looks*  like it should be a data transformation pipeline, but
>> >it's not - each step in the chain is mutating the original object,
>> >rather than creating a new one. That's a critical*problem*  with the
>> >idea, not a desirable feature.

> Except that it doesn't. The idea of using a different operator is that
> it should clearly be mutating the original object. It really IS
> obvious, at a glance, that it's going to be returning the existing
> object, because that operator means it will always be.

I agree with nick, this looks like a transformation chain. Each step 
transforming the "new" result of the previous step.

       seq = []->extend(get_data())->sort()



To make it pythonic ...


The operator you want is one for an in place method call. If we apply the 
"+=" pattern for the '__iadd__' method call syntax, to the more the general 
'.' method syntax, we get ".=", the in place method call syntax.

    seq = []
    seq .= extend(get_data())    # In place method call.

In place method calls seem quite reasonable to me.



And then to get the rest of the way there, allow chained "in place" method 
calls.

    seq = [] .= extend(get_data()) .= sort()

Which should be a separate pep from the ".=" enhancement.



BTW... allowing ".=" could mean a class could have one __iget_method__ 
attribute instead of multiple __ixxxx___ methods. (Or something like that.)

Cheers,
     Ron



More information about the Python-ideas mailing list