[Tutor] What does "sort" without parens do?

Gonçalo Rodrigues op73418@mail.telepac.pt
Fri Dec 13 12:09:02 2002


----- Original Message -----
From: "Terry Carroll" <carroll@tjc.com>
To: <tutor@python.org>
Sent: Friday, December 13, 2002 4:55 PM
Subject: [Tutor] What does "sort" without parens do?


>
> I made an error in a program, and Python's handling of it befuddles me.
> I had a list named "file_list"  that was full of instances of a class,
> each instance describing a file on a set of CDROMs (I'm indexing my MP3
> collection).
>
> To sort the list: I mistyped:
>
>   file_list.sort
>
> Okay, that's wrong.  I should have used:
>
>   file_list.sort()
>
> I did that, and everything worked fine.
>
> Now, I'm not surprised that the version without parens didn't work -- it's
> not supposed to.  But I'm intrigued that it didn't give a syntax error or
> exception, or, as far as I can tell, have any effect at all.  How did
> Python interpret that line?

In Python *everything* is an object - In particular functions, methods, etc
are objects with the same status and privelieges than others (like lists).
When Python sees something like

file_list.sort

It just looks for the attribute sort in the object (a list in this case)
file_list. Since it can't find it there, it goes to the class of file_list
and finds a sort attribute there. It then returns what it found with some
wrapping to make it a bound method - I'm being a little bit sloppy, but it
doen't matter. You could for example do

sorting_file_list = file_list.sort

Now sorting_file_list  is what is called a callable - it behaves much like a
function. The great difference is that it is a bound method - it "knows"
what object it applies (the list file_list in this case). At the syntactic
level you "call" it by sorting_file_list() - notice the parenthesis? It is
*exactly the same* as if you had done file_list.sort() directly.

>
> --
> Terry Carroll

HTH,
G. Rodrigues