It depends what you mean by 'scalar'. If you mean in the Perlish sense
(ie, numbers, strings and references), then that's really the only way
to do it in Python - there's no such thing as 'scalar context' or
anything - a list is an object just as much as a number is.

So, assuming you want a Things object to break if either a) all three
arguments aren't sequences of the same length, or b) all three
arguments aren't a number (or string, or whatever), this should work:

#Not tested.
class Things(object):
    def __init__(self, x, y, z):
        try:
            if not (len(x) == len(y) and len(y) == len(z)):
                raise ValueError('Things don't match up.')
        except TypeError:
            #one of x, y or z doesn't do __len__
            #check if they're all ints, then.
            if not (isinstance(x, int) and isinstance(y, int) and
                    isinstance(z, int)):
                raise ValuError('Things don't match up')
        #do stuff.

Personally, I find nothing wrong with having a separate Thing object
that can do validation for itself, and I think it's a pleasantly object
oriented solution

I'm also wondering why something like this could accept something other
than sequences if it depends on their length. If you just want to treat
non-sequences as lists with one value, then something like this is more
appropriate, and might lead to less redundancy in other places:

def listify(obj):
    try:
        return list(obj)
    except TypeError
        return [obj]

class Things(object):
    def __init__(self, *args):
        x, y, z = [listify(arg) for arg in args]
        if not (len(x) == len(y) and len(y) == len(z)):
            raise ValueError('Things don't match up')

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to