len() should always return something

Robert Kern robert.kern at gmail.com
Sat Jul 25 16:57:23 EDT 2009


On 2009-07-24 21:50, Dr. Phillip M. Feldman wrote:
> 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.

I have spent the last ten years writing scientific code in Python (i.e. that 
which otherwise might be written in Matlab), and I can guarantee you that you do 
not need to put such extra logic in practically every function. Even when 
naively translating code from Matlab, it's not often necessary.

By the way, are you familiar with numpy? If you are converting code from Matlab, 
you will almost certainly need it. We have a number of functions that make these 
kinds of operations easy when they are in fact necessary. For example, we have 
isscalar() and atleast_1d().

   def dumbfunc(xs):
     xs = numpy.atleast_1d(xs)
     for x in xs:
       print x

http://numpy.scipy.org/

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list