sufficiently pythonic code for testing type of function

John Machin sjmachin at lexicon.net
Wed Oct 11 01:55:39 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, raising an error otherwise.
>
> Is it enough to rely on side effects or absence thereof, or should I
> put return True in here somewhere?
>
> def test_obj_type(obj, types):
>   for type in types:
>     if isinstance(obj, type):
>       break
>     else:
>       raise ValueError, 'object is not in %s' % types
>

Hello Theerasak,

To answer your question: Either (a) return True if OK, False if not OK
or (b) make it like an assertion: raise an exception if not OK, do
nothing if OK. Returning True from the above function would be a rather
strange hybrid.

However:

1. if isinstance(obj, types[1] is true, but isinstance(obj, types[0])
is false, this would appear to raise ValueError. Is the indentation of
the else and raise what you intended?

2. In any case, since Python 2.2, no loop is necessary:

def test_obj_type(obj, types):
    if not isinstance(obj, types):
        raise ValueError, 'object is not in %s' % (types, )

If you don't want the assertion style, your "someone else" can call
isinstance directly.

3. And please notice the change in the raise line; if types is a tuple
of two or more items, the % operator treats it specially. As coded, you
would get this exception:
"TypeError: not all arguments converted during string formatting"

HTH,
John




More information about the Python-list mailing list