[Python-ideas] Method chaining notation

Ron Adam ron3200 at gmail.com
Mon Feb 24 08:14:52 CET 2014


On 02/23/2014 05:52 PM, Stephen J. Turnbull wrote:
> Ron Adam writes:
>
>   > The operator you want is one for an in place method call.
>
>   >     seq = [] .= extend(get_data()) .= sort()
>
> That looks like anything but Python to me.

Is it really all that different from this?

  >>> "Py" . __add__("th") . __add__("on")
'Python'

The '.=' just says more explicitly that self will be returned after the 
method call.

It wouldn't alter the string example here, since self isn't returned.  But 
for mutable objects, it's an explicit reminder that it mutates rather than 
returns a new object.

In the case that there is no __iget_method__ method, it would give an 
error.  So it's not a make everything into a chain tool.

 > If I really thought of
> that as a single operation, I'd do something like
>
>      class ScarfNSort(list):
>          def __init__(self):
>              self.extend(get_data())
>              self.sort()
>
>      seq = ScarfNSort()
>
> If it doesn't deserve a class definition, then the repeated references
> to 'seq' wouldn't bother me.
 >
> N.B. '.=' shouldn't be called "in-place": 'sort' and 'extend' are
> already in-place.  The word would be "chain," "cascade," or similar.

It's a chain only if you link more than one in sequence.

Cheers,
    Ron






More information about the Python-ideas mailing list