How do I chain methods?

Steven D'Aprano steve-REMOVE-THIS at cybersource.com.au
Mon Oct 25 04:49:37 CEST 2010


On Mon, 25 Oct 2010 09:39:47 +1000, James Mills wrote:

> On Mon, Oct 25, 2010 at 9:21 AM, chad <cdalten at gmail.com> wrote:
>> I just saw this technique used in python script that was/is used to
>> automatically log them in myspace.com. Hence the question.
> 
> Function/Method Chaining is probably used a lot in Python itself:
> 
>>>> x = 4
>>>> x.__add__(1).__sub__(3)
> 2
> 
> The implementation of many common operators return self (the object
> you're working with).


I can't think of any operations on built-ins that return self, except in 
the special case of an identity operation. And even then, it's not common:

>>> x = 2.5
>>> y = x.__add__(1)
>>> y is x
False
>>> y = x.__add__(0)
>>> y is x
False


Ah wait, no, I thought of one: __iadd__:

>>> x = [2.5]
>>> y = x.__iadd__([None])
>>> y is x
True

But:

>>> x = 2.5
>>> y = x.__iadd__(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'float' object has no attribute '__iadd__'



By the way, in case any newbies out there are reading... 

...if you're writing x.__add__(1).__sub__(3) instead of x + 1 - 3 then 
you're almost certainly doing it wrong.



-- 
Steven



More information about the Python-list mailing list