test if PyObject * points to real python object

Skip Montanaro skip at pobox.com
Wed Jun 23 21:52:17 CEST 2004


    David> With the Python/C API, how do i test if a given PyObject *
    David> actually points to a real/valid python object?

Wait and see if you get a core dump when you use it. <wink>

Seriously, you have no real way of knowing.  The PyObject struct is defined
as

    typedef struct _object {
            PyObject_HEAD
    } PyObject;

where PyObject_HEAD is #defined as 

    #define PyObject_HEAD                       \
            _PyObject_HEAD_EXTRA                \
            int ob_refcnt;                      \
            struct _typeobject *ob_type;

(_PyObject_HEAD_EXTRA is normally empty.)  You could dereference the ob_type
field, but that might be trash in which case you might get a core dump.  If
it is trash you won't know if it's because your PyObject* is invalid or that
it's valid but got stomped on.  This is C after all.  Pointers can reference
any bit of memory.

You can test for specific subclasses of PyObject using the defined macros
(PyString_Check, PyList_Check, etc).  All they do is compare the value of
the ob_type field against known statically allocated type objects, e.g.:

    #define PyLong_Check(op) PyObject_TypeCheck(op, &PyLong_Type)

If you're determined I suppose you could call all the Py*_Check macros until
one succeeds (warning: there are dozens).  If you get a match you can be
fairly confident that the pointer you have does actually reference a
PyObject struct of some sort.  If not, it may still be a PyObject*, just one
you hadn't expected.

If this answer doesn't help, perhaps you can add some detail to your
question.

Skip




More information about the Python-list mailing list