"Humane" programmer interfaces

Alex Martelli aleax at mail.comcast.net
Mon Jan 2 20:40:45 EST 2006


Dennis Lee Bieber <wlfraed at ix.netcom.com> wrote:
   ...
> > code goo.last than goo[-1].  For an analogy, consider, in Python,
> > somestr.startswith('glab') as a more readable equivalent of
> > somestr[:4]=='glab' -- the "why add?" question is easily answered,
> 
> Using constants for the example does obscure things a bit...

A little, yes, and I do agree that writing len('glab') rather than the
"magic number" constant 4 would make things clearer, as in your example:

>  if somestr[:len(needle)] == needle:

This is definitely more readable, and the same would apply if I tested
somestr[:len('glab')] == 'glab' -- the key point being that one knows
where that slice limit comes from, rather than having to guess.

But that doesn't really change the main point, that Python does offer
redundant ways to perform several tasks -- a general one (often based on
slicing) and a specialized one with a readable name -- as in this
example and several others I brought.  Yet another: you could always use
the more general 'extend' method to add just one element, via
somelist.extend([element]), but the more readable synonym
somelist.append(element) is also offered (and becomes thereby "the
obvious way" to perform this common task).  Having a '.last' property to
perform just the same task as a [-1] indexing is not a very different
concept -- I'm not saying it's obviously right, but criticizing it as
"obviously wrong" because of the [-1]-indexing equivalence is, IMHO, a
very misplaced viewpoint.  Much like I prefer using list(alist) to make
a copy (more readable), rather than the concise idiom alist[:] based on
slicing, I might well prefer to use alist.last rather than alist[-1], if
I had a choice (which doesn't mean I'd rather have a choice -- I think
that Python made the right tradeoff here, as in many other cases, but by
a very thin margin in this one case, IMHO).

That some (not all) of the numerous "general idioms" for which Python
offers more readable synonyms may require (or at least be best expressed
with) some len(...) call is hardly a big sub-issue -- some do, like e.g.
L[len(L):]=... as the equivalent of L.extend(...), some don't, like e.g.
del L[a:b] as the equivalent of L[a:b]=[], and yet the "alternative
readable synonym" gets offered anyway.


Alex



More information about the Python-list mailing list