len() should always return something

Dr. Phillip M. Feldman pfeldman at verizon.net
Fri Jul 24 22:50:54 EDT 2009


Here's a simple-minded example:

def dumbfunc(xs):
   for x in xs:
      print x

This function works fine if xs is a list of floats, but not if it is single
float.  It can be made to work as follows:

def dumbfunc(xs):
   if isinstance(xs,(int,float,complex)): xs= [xs]
   for x in xs:
      print x

Having to put such extra logic into practically every function is one of the
annoying things about Python.

Phillip


Diez B. Roggisch-2 wrote:
> 
> Dr. Phillip M. Feldman schrieb:
>> 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.
> 
> Can you show some example of where that is actually making a piece of 
> code more elegant?
> 
> Diez
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 
> 

-- 
View this message in context: http://www.nabble.com/len%28%29-should-always-return-something-tp24639361p24654439.html
Sent from the Python - python-list mailing list archive at Nabble.com.




More information about the Python-list mailing list