Boost logo

Boost :

From: Anton Gluck (gluc_at_[hidden])
Date: 2000-12-01 00:36:16


Dave,

> I suggest writing isinstance() in Python something like this.
>
> # untested! (not needed For Python 2.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
>
> # untested! For Python 1.5 or 2.0
> def is_instance(obj, type):
> return isinstance(obj, type) or _is_subclass(getattr(obj, '__class__',
> None), type)

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".

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)

I merely changed isinstance in your code to my _is_instance. On my setup,
where CatVar is a subclass of ClusterVar and both are extension classes,
this test code worked:

class A: pass
class B(A): pass
class C: pass
a = A()
b = B()
if isinstance(a, A): print "a is A"
if is_instance(a, A): print "same"
if isinstance(b, B): print "b is B"
if is_instance(b, B): print "same"
if isinstance(b, A): print "b is A"
if is_instance(b, A): print "same"
if isinstance(a, C): print "a is C"
else: print "a is not C"
if is_instance(a, C): print "same"
else: print "also no"
c = ContVar()
try:
        if isinstance(c, ContVar): print "c is ContVar"
except TypeError:
        print "I know..."
if is_instance(c, ContVar): print "c is ContVar"
if is_instance(c, ClusterVar): print "c is ClusterVar"

This is the output:

a is A
same
b is B
same
b is A
same
a is not C
also no
I know...
c is ContVar
c is ClusterVar

I hope this is helpful.

Toni


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