Why return None?

Roy Smith roy at panix.com
Wed Aug 25 14:59:07 CEST 2004


In article <uK%Wc.213074$gE.193548 at pd7tw3no>,
 Martin DeMello <martindemello at yahoo.com> wrote:

> Dan Sommers <me at privacy.net> wrote:
>  
> > If list.sort returned the sorted list, how many lists would there be
> > after this code executed?
> > 
> >     original_list = a_function_that_returns_a_list( )
> >     sorted_list = original_list.sort( )
> 
> One - sorted_list would be a reference to the (now sorted) original
> list. The newbie problem could be solved by having <verb> and <verbed>
> versions of each destructive method - i.e. list.sort() to sort the list
> in-place and return it, and list.sorted() to return a new, sorted list,
> and experienced users could chain methods and all that other good stuff.
> 
> martin

The problem with sort() vs. sorted() is that it's obscure.  I'm not a 
big fan of quoting gospel, but it seems to me that it violates the 
gospel of "explicit is better than implicit".

If I took 10 programmers who were generally familiar with typical OO 
syntax, but not specifically with Python and asked them what list.sort() 
and list.sorted() did, I imagine all of them would say something like, 
"Well, they both obviously sort a list, and clearly the existence of two 
different methods means they do it differently somehow, but I can't for 
the life of me guess what the difference is".

Explicit would be something like having two methods named in ways that 
people could figure out without having to RTFM:

list.sort () ==> returns a sorted copy of the list
list.sort_in_place () ==> sorts in place, returns None

or if you prefer to do it the other way:

list.sort () ==> sorts in place, returns None
list.sort_copy () ==> returns a sorted copy of the list

But, personally, I find that all kind of silly; IMHO, list.sort () 
should have just returned self to begin with and then we wouldn't be 
having this discussion.

heretic-ly yours.



More information about the Python-list mailing list