Boost logo

Boost :

From: David Abrahams (abrahams_at_[hidden])
Date: 2000-11-26 09:08:55


From: "Anton Gluck" <gluc_at_[hidden]>

> Is there a difference between py_cpp extension classes and regular Python
> classes when it comes to isinstance(object, classname)?

In Python 1.5.x, there definitely is a difference. The new support for
isinstance() on extension classes in Python 2.0 should handle your case.
Though I haven't tested it with py_cpp, the 2.0 sources seem to indicate
that it will "just work"... oops! Harrumph! It looks like someone decided
that extension classes couldn't also be type objects in Python 2.0. If the
2nd argument is a type but is not a builtin Class, it appears that Python
2.0 reverts to Python 1.5.x behavior:

static PyObject *
builtin_isinstance(PyObject *self, PyObject *args)
{
        PyObject *inst;
        PyObject *cls;
        PyObject *icls;
        static PyObject *__class__ = NULL;
        int retval = 0;

        if (!PyArg_ParseTuple(args, "OO:isinstance", &inst, &cls))
                return NULL;

        if (PyClass_Check(cls)) {
                if (PyInstance_Check(inst)) {
                        PyObject *inclass =

(PyObject*)((PyInstanceObject*)inst)->in_class;
                        retval = PyClass_IsSubclass(inclass, cls);
                }
        }
        else if (PyType_Check(cls)) {
                retval = ((PyObject *)(inst->ob_type) == cls);
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ HERE
        }
...

At least in Python 2.0, issubclass doesn't seem to make any such
distinction.

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)

Good luck,
Dave


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