This executes as I\'d expect:
>>>x=[]
>>>x.append(3)
>>>x
[3]
Why does the following return None?
&g
If the question is "why is x
None
?", then it's because list.append
returns None
as others say.
If the question is "why was append
designed to return None
instead of self
?" then ultimately it is because of Guido van Rossum's decision, which he explains here as it applies to a related case:
https://mail.python.org/pipermail/python-dev/2003-October/038855.html
I'd like to explain once more why I'm so adamant that sort() shouldn't return 'self'.
This comes from a coding style (popular in various other languages, I believe especially Lisp revels in it) where a series of side effects on a single object can be chained like this:
x.compress().chop(y).sort(z)
which would be the same as
x.compress()
x.chop(y)
x.sort(z)
I find the chaining form a threat to readability;
In short, he doesn't like methods that return self
because he doesn't like method chaining. To prevent you from chaining methods like x.append(3).append(4).append(5)
he returns None
from append
.
I speculate that this could perhaps be considered a specific case of the more general principle that distinguishes between:
Of course the Python language doesn't make any such distinction, and the Python libraries do not apply the general principle. For example list.pop()
has a side-effect and returns a value, but since the value it returns isn't (necessarily) self
it doesn't violate GvR's more specific rule.