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

Michael Spencer mahs at telcopartners.com
Sat Dec 3 23:18:37 EST 2005


Brendan wrote:
...
> 
> 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
> 
...
> 
> 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.
> 

Yes, but depending on what you want to do with Things, it might indeed make 
sense to convert its arguments to a common sequence type, say a list.  safelist 
is barely more complex than sLen, and may simplify downstream steps.

def safelist(obj):
     """Construct a list from any object."""
     if obj is None:
         return []
     if isinstance(obj, (basestring, int)):
         return [obj]
     if isinstance(obj, list):
         return obj
     try:
         return list(obj)
     except TypeError:
         return [obj]

class Things(object):
     def __init__(self, *args):
         self.args = map(safelist, args)
         assert len(set(len(obj) for obj in self.args)) == 1
     def __repr__(self):
         return "Things%s" % self.args

  >>> Things(0,1,2)
  Things[[0], [1], [2]]
  >>> Things(range(2),xrange(2),(0,1))
  Things[[0, 1], [0, 1], [0, 1]]
  >>> Things(None, 0,1)
  Traceback (most recent call last):
    File "<input>", line 1, in ?
    File "C:\Documents and Settings\Michael\My 
Documents\PyDev\Junk\safelist.py", line 32, in __init__
      assert len(set(len(obj) for obj in self.args)) == 1
  AssertionError


Michael






More information about the Python-list mailing list