Question about consistency in python language

Kay Schluehr kay.schluehr at gmx.net
Fri Sep 9 17:38:39 EDT 2005


Mike Meyer wrote:

> Yes, but the function "sorted" is more useful than a list method
> "sorted" in a duck typing language.

I don't see what this has to do with "duck typing"? sorted() is simply
a generic function accepting different types. I'm not aware that
sorted() requires a specific interface of those types it accepts.

>
> The function sorted works on all iterators. I can do:
>
> >>> def t(n):
> >>>   for i in range(n):
> >>>     yield i
> >>> ...
> >>> print sorted(t(5))
>
> and have it work.
>
> If sorted were a method of a class - the it'd have to be implemented
> again for every class iterable class. Either that, or you'd have to
> create an abstract parent of all iterable classes to add it to - which
> seems more appropriate for a B&D language than Python.

Instead of extending a class hierarchy it might even be possible to
hook a trait into the class by means of a __traits__ attribute.

http://fsl.cs.uiuc.edu/~mhills/presentations/TraitsPresentation.pdf

Generators as well as lists and tuples would provide a sortable trait.
The sorted() function could remain available for convenience.

> And even if you do add the abstract class, how do you make my example
> work without explictly converting the iterator to a list type?

I don't know how sorted() is implemented? A naive implementation would
in fact be nothing else then:

def sorted(iter):
    l = list(iter)
    l.sort()
    return l

Kay




More information about the Python-list mailing list