Boost logo

Boost :

From: David Abrahams (abrahams_at_[hidden])
Date: 2000-12-01 08:32:20


----- Original Message -----
From: "Anton Gluck" <gluc_at_[hidden]>

> I've tried to implement an isinstance() for Python 1.5.2 that would work
> with extension classes following your suggestion. However, on closer look,
> the above code will create the same problem as the original
> isinstance(obj, type) since this is what it calls too. You might remember
> that the error with isinstance() is "second argument must be a class".

That's a dumb error message, because isinstance('x', type('x')) works, and
type('x') isn't a class. In any case, I know what they're checking
internally: if the type of the 2nd argument is not types.TypeType, it must
be a class. In any case, you're right: my code wouldn't work. I was trying
to hijack the builtin isinstance() for performance reasons, but Python will
reject that.

> This here worked for me, but I don't know how generally applicable it
> would be:
>
> def _is_instance(obj, type):
> if obj.__class__ == type:
> return 1
> else:
> return 0
>
> def _is_subclass(t1, t2):
> for b in getattr(t1, '__bases__', ()):
> if b is t2 or _is_subclass(b, t2):
> return 1
> return 0
>
> def is_instance(obj, type):
> return _is_instance(obj, type) or _is_subclass(getattr(obj,
> '__class__', None), type)

The problem with this approach is that it will fail with an error for
isinstance('x', type('x')). I think the right answer is something like this:

def is_instance(obj, t):
    return type(obj) == t or _is_subclass(getattr(obj, '__class__', None),
type)

of course, this doesn't go out of its way to replicate Python's error
reporting.
Thanks for finding my bug.

-Dave


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk