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

Alex Martelli aleax at mail.comcast.net
Sat Dec 3 21:38:17 EST 2005


Sam Pointon <free.condiments at gmail.com> wrote:
   ...
> 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.')

Careful though: this does NOT treat a string as a scalar, as per your
parenthetical note, but rather as a sequence, since it does respond
correctly to len(...).  You may need to specialcase with checks on
something like isinstance(x,basestring) if you want to treat strings as
scalars.


Alex



More information about the Python-list mailing list