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

Tim Peters (tim@ksr.com)
Mon, 13 Sep 93 23:01:52 -0400

> [steve, noting that [].sort(), [].reverse(), ..., return None instead
> of the modified object, making natural-enough constructs like
> string.split( file.readline() ).sort()
> surprising
> ]
> ...
> ( And I can't even think of some likely + reasonable code that would
> be broken by the change. ...

For a reasonable counterexample, how about every program you have <0.1
grin>? That is, whenever you have

thing.sort()

now, it yields None, and _because_ it yields None specifically, Python
doesn't print the value:

>>> [1,2,3] # non-None result is printed
[1, 2, 3]
>>> None # None result is not printed
>>>

So if thing.sort() (or reverse or append) were to return the sorted
(reversed, appended) object instead, every existing line like that would
start producing output. Yeech!

I suspect Jaap would disagree, but as a pragmatic matter I like Python's
mix of functional, procedural, and OO flavors -- different bullets for
different beasts. It's hard to judge which flavor is best for each
built-in concept, though.

Anyway, here's a cheap (& I dare say obvious <wink>) workaround I use.
Haven't upgraded this since [].sort() grew its optional comparison-
function argument, but that's clearly easy to add:

def sort(thing):
thing.sort()
return thing

Then, e.g.,
process(sort(string.split( file.readline() )))

works fine. I too dislike the

temp = string.split( file.readline() )
temp.sort()
process( temp )

alternative.

non-decreasing-ly y'rs - tim

Tim Peters tim@ksr.com
not speaking for Kendall Square Research Corp