How do I chain methods?
tjreedy at udel.edu
Mon Oct 25 19:48:21 CEST 2010
On 10/24/2010 11:42 PM, Chris Rebert wrote:
> On Sun, Oct 24, 2010 at 4:11 PM, James Mills
> <prologic at shortcircuit.net.au> wrote:
>> On Mon, Oct 25, 2010 at 9:02 AM, Chris Rebert<clp2 at rebertia.com> wrote:
>>> Method chaining is usually* not idiomatic in Python.
>> I don't agree but anyway... I've just not seen it commonly used
>> amongst python programmers.
> If Python wanted to encourage method-chaining-style, then list.sort(),
> list.reverse(), and several other built-in type methods would (ala
> Ruby) return self rather than None. Since they don't, and since
> "uncommon idiom" is a near-oxymoron, I think we can safely conclude
> that method chaining isn't idiomatic in Python.
It is intentionally not idiomatic for methods that mutate or otherwise
operate strictly by side-effect, as in the OP example.
It *is* idiomatic for methods that return new objects.
>>> s = ' abc def '
And, of course, it is used internally to implement expressions with
operators that also produce new objects.
>>> 3*2+1 == 3 .__mul__(2) . __add__(1)
Terry Jan Reedy
More information about the Python-list