Why return None?
maxm at mxm.dk
Wed Aug 25 12:49:18 CEST 2004
Martin DeMello wrote:
> Anthony Baxter <anthonybaxter at gmail.com> wrote:
>>On Wed, 25 Aug 2004 08:26:26 GMT, Martin DeMello
>><martindemello at yahoo.com> wrote:
>>>It seems to be a fairly common pattern for an object-modifying method to
>>>return None - however, this is often quite inconvenient.
>>list.reverse() modifies the list in place. The python idiom is that
>>these don't return a reference to the modified list. Although note the
> Yes, but why? I mean, is there either an advantage to returning None or
> some inherent danger in returning self?
It is a design philosophy. Explicit is better than implicit.
what would you expect a_list.sort() to return?
If it returns a list, you would expect it to be a sorted copy of the
list. Not the list itself.
But for performance reasons the list is sorted in place.
So if you modify the list in place, why should sort() then return the list?
That the sort() method returns a None is actually a pedagocical tool to
tell the programmer that the list is modified in place.
If it had returned the list the programmer would later be surprised to
find that the list had been modified. It would seem like hard to find
nasty side effect. The way it is now is very explicit and easy to find out.
regards Max M
More information about the Python-list