len() should always return something
Peter Otten
__peter__ at web.de
Fri Jul 24 03:07:03 EDT 2009
Dr. Phillip M. Feldman 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.
Python should not blur the distinction between vectors an scalars like that.
Instead of trying to be clever you should pass a vector with a single item
and send mylen() to /dev/null.
On a general note, I think one of Python's strengths is that it consistently
/avoids/ this kind of cleverness.
A prominent example is the handling of "1" + 1.
Peter
More information about the Python-list
mailing list