len() should always return something

Luis Zarrabeitia kyrie at uh.cu
Fri Jul 24 13:46:10 EDT 2009


On Friday 24 July 2009 11:58:36 am Phillip M. Feldman wrote:
> I've been converting Matlab codes to Python.  In Matlab, a scalar is just a
> one-by-one matrix and has a length of 1.  This convention seems no less
> arbitrary to me than Python's convention that the concept of length is not
> applicable to ints and floats.

Are you sure it isn't? (as opposed to being tainted by matlab?).

Almost everywhere, a scalar and a tuple are different things. How many 
elements are "inside" the number 7? If you assume that 7 is a matrix, why 
should it be a two-dimensional matrix? Why not a vector, or a three 
dimensional matrix instead? (I don't use matlab, but in octave, size(7) 
returns [1,1], not [1] or [1,1,1,1]).

That seems even more arbitrary to me. Of course, in a language like Matlab, 
that assumes that everything is a matrix, it makes sense for scalars to be 
mapped to a useful matrices. But that assumption is not natural.

Even pure math makes a difference between scalars and vectors. Matrix x Matrix 
multiplication is not always defined (even when the second matrix contains 
exactly one element), while Matrix x Scalar always is. (Octave, btw, will 
demote a two-dimensional 1x1 matrix to a scalar for Matrix multiplication, 
which may hide errors)

If you are converting from matlab, I'd say you have biggest things to worry 
about. As you said, you can just replace the len function (even safer may be 
to do [1]). Assignment, for instance, is /very/ different.

> If there is only a single measurement, it is reasonable to allow the calling 
> program to pass a scalar without wrapping it up into a list or array.

I try to avoid those automatic conversions, on the long run, I believe that 
most of them make the code more confusing for the caller. If you feel that 
you must allow that, my suggestion would be to create a method that will 
ensure that what you receive is a list (or whatever) and coerce its argument 
if not, and call that one at the beginning of your methods.

Regards,

[1] this will define len for any object, not only int and floats.
===
def size(x):
    try:
        return len(x)
    except TypeError:
        return 1,1
===

-- 
Luis Zarrabeitia (aka Kyrie)
Fac. de Matemática y Computación, UH.
http://profesores.matcom.uh.cu/~kyrie



More information about the Python-list mailing list