Consistency in Python

Brendon Towle btowle at carnegielearning.com
Fri Aug 25 09:11:46 EDT 2006


> Date: 25 Aug 2006 04:22:37 -0700
> From: "Paul Boddie" <paul at boddie.org.uk>
> Subject: Re: Consistency in Python
> To: python-list at python.org
> Message-ID: <1156504957.511315.223360 at i3g2000cwc.googlegroups.com>
> Content-Type: text/plain; charset="iso-8859-1"
>
> Paul McGuire wrote:
>>
>> But with mutators that return self, a client could write any of  
>> these:
>>
>> bx = Box().length(100).width(50).height(20)
>> bx = Box().width(50).height(20).length(100)
>> bx = Box().width(50).length(100).height(20)
>> ...etc...
>>
>> and the results are the same.
>
> This is very convenient, and I've often thought about doing such  
> things
> in my own APIs, but there can sometimes be subtle problems introduced
> into programs when you decide to change the nature of such a mutator,
> or if you have another type/class whose mutators are of a different
> nature, such that the width method produces a new Box object (which is
> quite similar to what the questioner seemed to have in mind)  
> instead of
> mutating (or failing to mutate) the existing object.
>
> Indeed, it may be important to know whether you're creating new  
> objects
> or not, and without metadata the most convenient way to communicate
> this is quite probably to define a rigid interface (after all, why
> should width or append return an object?) which cannot be implemented
> on immutable things.

So, it's possible that the above answers the question I have and I'm  
just not clever enough to see the answer. But:

I had a case where I wanted to extract and return the top N elements  
of a list (where "top" meant "smallest numeric value"; the  
alternative for "largest numeric value" is a trivial modification).  
To me, the obvious answer was:

def topNElements(lst, n):
     return lst.sort()[:n]

But, of course, that fails with a TypeError, because lst.sort()  
returns None, which is not subscriptable. The function really needs  
to be:

def topNElements(lst, n):
     lst.sort()
     return lst[:n]

It gets worse if I want to include an invariant in the list before I  
sort it:

def bogusTopNElementsWithInvariant(lst, n):
     return lst.append(INVARIANT).sort()[:n]

def topNElementsWithInvariant(lst, n)
     lst.append(INVARIANT)
     lst.sort()
     return lst[:n]

So, my question is: Someone obviously thought that it was wise and  
proper to require the longer versions that I write above. Why?

B.

-- 
Brendon Towle, PhD
Cognitive Scientist
+1-412-690-2442x127
Carnegie Learning, Inc.
The Cognitive Tutor Company ®
Helping over 375,000 students in 1000 school districts succeed in math.


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20060825/716ed3ba/attachment.html>


More information about the Python-list mailing list