[Python-ideas] Method chaining notation

Ron Adam ron3200 at gmail.com
Mon Feb 24 16:01:07 CET 2014



On 02/24/2014 01:34 AM, Andrew Barnert wrote:
>> >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'
> Well, yes, it is. But, more importantly, who cares? That code is horribly unreadable and unpythonic. OK, I don't think PEP8 has a guideline saying "don't call __add__ when you can just use +", but only because it's so obvious it doesn't need to be stated. (And I'm pretty sure it_does_  have a guideline saying not to put spaces around the attribute dot.)
>
> So, is your argument is "my code looks kind of like some horribly unreadable and unpythonic, but legal, code, and therefore it should also be legal despite being unreadable and unpythonic?"

Wow, tough crowd here.. :-)

Both the separation of the '.', and the use of the already special __add__ 
isn't important as far as the actual suggestion is concerned.  Those are 
unrelated style issues.

You would probably see it used more often like this...

    def names(defaults, pos_names, pos_args, kwds):
        return  {}.=update(defaults) \
                  .=update(zip(pos_names, pos_args) \
                  .=update(kwds)


Normally .update returns None.  The reason for that is so that it's clear 
you are mutating an object instead of creating a new one.

By using .=, it can return self, but still maintain the clarity between 
mutation and non-mutation.

This particular syntax is consistent with the use of OP+equal to mean 
mutate in place.  But you might prefer, "..", or something else.

The other alternative is to use a function.  But it would be difficult to 
get the same behaviour along with the same efficiency.

Regards,
    Ron



More information about the Python-ideas mailing list