[Python-ideas] Method chaining notation

spir denis.spir at gmail.com
Fri Feb 21 23:00:54 CET 2014


On 02/21/2014 10:37 PM, Terry Reedy wrote:
> On 2/21/2014 12:30 PM, Chris Angelico wrote:
>
>> It's common in languages like C++ to return *this by reference if
>> there's nothing else useful to return. It's convenient, it doesn't
>> cost anything much, and it allows method chaining. The Python
>> convention, on the other hand, is to return self only if there's a
>> very good reason to,
>
> Off the top of my head, I cannot think of any methods that return self. (If
> there are some, someone please remind or inform me.)

It is (in my experience) a common practice, precisely to allow method chaining, 
in diverse libs. The most common cases happen at object construction, where 
chaining adds or changes diverse object properties. This is also at times 
combined with overloading of language features. In the following, from a parsing 
lib, the init method returns its object, and __call__ is overriden to a method 
that sets an match actions on the pattern:

	symbol_def = Compose(id, ":=", expr)(put_symbol)

[This defines a patten for symbol defs (read: assignment of a new var); when the 
pattern matches, the symbol is put in a symbol table.] However, this is probably 
only ok for such libs that developpers are forced to study intensely before 
being able to use them efficiently. Otherwise, in itself the code is pretty 
unreadable I guess.

Also, I don't find the idea of having a builtin construct for such hacks a good 
idea. Libs for which this may be practicle can return self --end of the story.

d


More information about the Python-ideas mailing list