My other pet python peeve - .sort(),.reverse(), etc. return None

Steven D. Majewski (sdm7g@elvis.med.virginia.edu)
Mon, 13 Sep 1993 14:23:19 -0400

Although I'm generally a python fan and booster, there are a couple
of quirks in the language that I sometimes find frustrating. ( Tim
and I were discussing a few of them, offline, in a thread started
by my 'obfuscated python' post. )

Some of them may be unavoidable features of other aspects of python's
syntax and/or model of execution. But one that often catches me,
because it seems (to me) rather arbitrary is the fact the some of
the list methods, like .sort, .reverse, .append, all return None.
I would think it preferable to return the new list.

Why?
[ I know I may have to await Guido's return to get an authoritive
answer. ]

The only reason that comes to mind, is that that design feature was
intended as a reminder that those methods are not, strictly speaking,
_functions_, but _procedures_ that produce side effects: "whatch out! -
x.sort() is going to change the value of x - not just return a NEW
sequence!" )

To a C and/or Lisp programmer, who is used to the idea that everything
is a function - some are not PURE side-effect-less functions, and some
don't return anything useful, but they are all functions, this does
not seem a very intuitive distinction. ( Maybe it *does( if you are
comming from Modula-[23]. I don't know. )

What's more: there is nothing to stop you from SAYING:

[ 1,2,3,4 ].sort()
[ 1,2,3,4 ].append( 5 )
[ 1,2,3,4 ].reverse()

all of which, of course, return None, NOT the result of applying
method to the anonymous sequence. ( An exception would seem to be
called for here, although, I don't expect that .sort() has any way
in hell of KNOWING that it is being called on an anonymous list. )

So I can't say, for example:

string.split( file.readline() ).sort()

[ In practice, lack of append() returning a value isn't usually a
problem: the expression is typically part of a 'return' or an
assignment, so, for example: "return string.join( list ) + '\n'"
is the typical idiom. ]

I know this isn't Guido's style. But it's *MY* style, and I'm
fond of it, ( as you can probably tell from my 'obfuscated python' ;-)
and it *seems* (IMHO) to be a rather _arbitrary_ restriction.
( And I can't even think of some likely + reasonable code that would
be broken by the change. I can't think that anyone ever *tests*
that "list.sort() == None" - since that is, in fact, the only
possible return value. )

-Steve Majewski (804-982-0831) <sdm7g@Virginia.EDU>
-Univ. of Virginia Department of Molecular Physiology and Biological Physics