len() should always return something

Chris Rebert clp2 at rebertia.com
Fri Jul 24 03:02:28 EDT 2009


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 -
http://www.python.org/dev/peps/pep-0020/).

Specifically:
- 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.

If you'd explain the situation that prompts you to find this
redefinition necessary, I'm sure someone can suggest a better
approach.

Cheers,
Chris
-- 
http://blog.rebertia.com



More information about the Python-list mailing list