Why return None?

Dave Opstad dave.opstad at agfamonotype.com
Wed Aug 25 16:30:53 CEST 2004


In article <412c6edb$0$258$edfadb0f at dread12.news.tele.dk>,
 Max M <maxm at mxm.dk> wrote:

> 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.

But isn't the fact that the list is modified in place incidental to the 
fact of sorting? One is an implementation detail, and the other is the 
semantic meaning you're trying to express.

In my opinion, it would make more sense to have:

[1, 3, 4, 2].sort() return [1, 2, 3, 4]
(1, 3, 4, 2).sort() return (1, 2, 3, 4)
'1342'.sort() return '1234'

and so on. As it is, we have sort working on lists but not on immutable 
sequences, which is inconvenient at times.

Just my tuppence.
Dave



More information about the Python-list mailing list