[Tutor] Need Explanation...

Steven D'Aprano steve at pearwood.info
Sat Dec 10 17:46:11 CET 2011


Alan Gauld wrote:
[...]
> Because app() returns the result of append().
> But append() returns None, since it modifies the list in place.
> 
> This is one of the few features of Python I dislike. It would not have 
> been difficult to make these modifier methods return the thing modified. 
> This style would then allow chained methods.

Very true. It would be useful to be able to write:

a = [1, 2, 3]
a.append(4).insert(0, 0)

But...

> We do it with strings:
> 
> "foobar is a string".rstrip('ing').upper()
> 
> because strings are immutable. But we could have done it with other 
> sequence types too. Sadly we didn't and history/tradition leaves us with 
> these counterintuitive modifiers that return None. It catches everybody 
> out at some point...

...the alternative would also have caught out everybody at some point. 
Consider a hypothetical Python where mutator methods returned a result:

a = [1, 2, 3]
b = a.append(4)

Does this mean...?

     * append 4 to a, then return a (and therefore a and b are
       alternative names for the same list)

     * append 4 to a, then return a copy of a (and therefore a
       and b are different lists that merely have the same
       content)

     * make a copy of a, then return the copy with 4 appended
       (and therefore a keeps its old value and b gets the new
       value)


Since each of the behaviours are reasonable and useful under some 
circumstances, regardless of which behaviour was choosen for append, it would 
catch out some people some time.

append() returning None is probably the least worst decision, since the error 
is obvious and so will likely be discovered as close as possible to the source 
of the error, rather than being subtle and so likely to cause hard-to-diagnose 
bugs.

A better alternative would be for Python to have procedures as well as 
functions/methods, so that:

b = a.append(4)

would raise an exception immediately. This would require the language to 
distinguish between "returning None" and "doesn't return anything", which I 
believe would be a good thing.


-- 
Steven


More information about the Tutor mailing list