[Python-ideas] Method chaining notation
Ron Adam
ron3200 at gmail.com
Mon Feb 24 18:03:39 CET 2014
On 02/24/2014 09:16 AM, Steven D'Aprano wrote:
> On Mon, Feb 24, 2014 at 09:01:07AM -0600, Ron Adam wrote:
>
>> >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.
> How does the update method know whether it is being called via . or via
> .= ? I'm trying to understand how you think this is supposed to work,
> and not having much success. Can you give a sketch of how this .= thingy
> is supposed to operate?
>
>> >The other alternative is to use a function. But it would be difficult to
>> >get the same behaviour along with the same efficiency.
> I don't see how you can compare the efficiency of code that can be
> written now with code that doesn't exist yet. How do you know how
> efficient your __iget_method__ suggestion will be?
First off, I need to be more consistent with names. Apologies for that
added confusion. I've been just trying to get out the gist of the idea
that feels right to me, but haven't worked through the finer details, so
for now on, I'll try to be more precise.
The byte code for '.' and '.=' will be nearly identical. The "LOAD_ATTR"
would be replaced by another byte code. That byte code would add a light
wrapper in (C) to check for None, an return self. By doing that, the
CALL_FUNCTION byte code deosn't need to change, and there's no need to add
the check for None in the bytecode. (Although that's doable too.)
Normally a method access with a "." is done with the LOAD_ATTR bytecode,
which in turn calls the objects __getattribute__ method. (Is this correct?)
For the .= examples, lets use LOAD_I_ATTR for the bytecode and
__getiattribute__. (Or other names if you think they would be better.)
The .= would differ by using (from the AST) a "LOAD_I_ATTR" in the byte
code, which would call a __getiattribute__.
If you use ".=" on an object without a __getiattribute__ it would give an
error saying you can't mutate that object.
When you use ".=" with a method on a mutable object, the call would expect
None, and return self. (giving an error if it gets something other than
none.) This is different, but not incompatible.
This has no effect on using '.' with immutable or mutable objects.
Cheers,
Ron
More information about the Python-ideas
mailing list