sufficiently pythonic code for testing type of function

Bruno Desthuilliers onurb at xiludom.gro
Wed Oct 11 04:29:16 EDT 2006


Theerasak Photha wrote:
> I wrote this for someone else to take an object and list of types,
> then check if obj is one of those types, 

This is already what isinstance(obj, tuple_of_types) does.

> raising an error otherwise.
> 
> Is it enough to rely on side effects or absence thereof, or should I
> put return True in here somewhere?

What for ?

> def test_obj_type(obj, types):
>  for type in types:
>    if isinstance(obj, type):
>      break
>    else:
>      raise ValueError, 'object is not in %s' % types



def checkinstanceof(obj, types):
  if not isinstance(obj, types):
    raise ValueError('object is not an instance of %s' % str(types))


Now the real question : what if the object is not an instance of any of
the types, but still support the expected interface ?

> -- Theerasak


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list