Checking length of each argument - seems like I'm fighting Python

Brendan spam4bsimons at yahoo.ca
Sat Dec 3 18:50:25 EST 2005


There must be an easy way to do this:

For classes that contain very simple data tables, I like to do
something like this:

class Things(Object):
    def __init__(self, x, y, z):
        #assert that x, y, and z have the same length

But I can't figure out a _simple_ way to check the arguments have the
same length, since len(scalar) throws an exception.  The only ways
around this I've found so far are

a)  Cast each to a numeric array, and check it's dimension and shape.
This seems like far too many dependencies for a simple task:

def sLen(x):
    """determines the number of items in x.
    Returns 1 if x is a scalar. Returns 0 if x is None
    """
    xt = numeric.array(x)
    if xt == None:
        return 0
    elif xt.rank == 0:
        return 1
    else:
        return xt.shape[0]

b) use a separate 'Thing' object, and make the 'Things' initializer
work only with Thing objects.  This seems like way too much structure
to me.

c) Don't bother checking the initializer, and wait until the problem
shows up later.  Maybe this is the 'dynamic' way, but it seems a little
fragile.

Is there a simpler way to check that either all arguments are scalars,
or all are lists of the same length?  Is this a poor way to structure
things?  Your advice is appreciated
   Brendan
--
Brendan Simons




More information about the Python-list mailing list