sufficiently pythonic code for testing type of function

Ben Finney bignose+hates-spam at benfinney.id.au
Wed Oct 11 01:44:05 EDT 2006


"Theerasak Photha" <hanumizzle at gmail.com> writes:

> 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

Why have you re-implemented (a less-functional version of) 'isinstance'?

    >>> help(isinstance)
    Help on built-in function isinstance in module __builtin__:

    isinstance(...)
        isinstance(object, class-or-type-or-tuple) -> bool

        Return whether an object is an instance of a class or of a subclass thereof.
        With a type as second argument, return whether that is the object's type.
        The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for
        isinstance(x, A) or isinstance(x, B) or ... (etc.).

    >>> isinstance(3, (int, float))
    True

-- 
 \       "Yesterday I told a chicken to cross the road. It said, 'What |
  `\                                          for?'"  -- Steven Wright |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list