len() should always return something
steve at REMOVE-THIS-cybersource.com.au
Fri Jul 24 15:05:11 EDT 2009
On Fri, 24 Jul 2009 00:02:28 -0700, Chris Rebert wrote:
> On Thu, Jul 23, 2009 at 11:35 PM, Dr. Phillip M.
> Feldman<pfeldman at verizon.net> wrote:
>> Some aspects of the Python design are remarkably clever, while others
>> leave me perplexed. Here's an example of the latter: Why does len()
>> give an error when applied to an int or float? len() should always
>> return something; in particular, when applied to a scalar, it should
>> return a value of 1. Of course, I can define my own function like this:
>> def mylen(x):
>> if isinstance(x,int) or isinstance(x,float): return 1 return len(x)
>> But, this shouldn't be necessary.
> The problem is that redefining len()/length/size that way would violate
> several principles of Python's design (The "Zen" of Python -
> - Explicit is better than implicit.
> - Special cases aren't special enough to break the rules.
> - Errors should never pass silently.
> - In the face of ambiguity, refuse the temptation to guess.
Chris, I'm curious why you think that these Zen are relevant to the OP's
Re explicit vs implicit, len(42) is just as explicit as len([42, 23]).
Arguably (I wouldn't argue this, but some people might) ints aren't
"special enough" to break the rule that len(obj) should always return
(I don't actually agree, but some people might be able to produce a
coherent argument why len() should apply equally to all objects.)
Re errors passing silently, the OP doesn't believe that len(42) should be
an error, so that's not relevant.
And there's nothing ambiguous about len(42).
I agree with the current Python behaviour, but I don't think there's
anything in the Zen to support it. As far as I know, there is no
programming language which treats scalars like ints as if they were
vectors of length 1, which makes Python's choice to make ints unlengthed
More information about the Python-list