Checking the type of a PyObject

wim delvaux wim.delvaux at adaptiveplanet.com
Sun Aug 12 13:01:35 EDT 2001


your suggestion was what I needed,   The stirng and int were merely
examples.  In fact the object
that would be passed as first argument would be a real object.  So only
your suggestion would work.

Question remains.  How can I get access to the PyString_Type variable
(buffer) declared in the extension module (if I remember)
for those abstract objects, if you do not know the name of the buffer
but only the name of the type.

Example.  Suppose you have extended with 2 types TypeA and TypeB (both
non-builtin of course)

How do you get access to the TypeA_Type and TypeB_Type type descriptors.

i.e. Is there a call like

    PyGetType( TypeA)

With which one could write

        PyObject theType = PyObject_Type(FirstArg);

         if( theType == Py_GetType( TypeA ) ) {
           /* now you know FirstArg is of typeA
         } ....

        Py_DECREF(theType);    /* when done with it */

Or perhaps

    if ( PyObject_IsOfType( FirstArg, TypeA) ) ) {

    }

Thanx again



Alex Martelli wrote:

> "Rainer Deyke" <root at rainerdeyke.com> wrote in message
> news:Hdod7.27408$c8.8315711 at news1.denver1.co.home.com...
>     ...
> > One approach would be the obvious:
> >
> > Mod_Function( PyObject *self, PyObject *args )  {
> >   char * String;
> >   long IVal;
> >   if (PyArg_ParseTuple( args, "s", &String )) {
> >     /* do something with String */
> >   } else if (PyArg_ParseTuple( args, "i", &IVal)) {
> >     /* do something with IVal */
>
> One caveat: I think you need to reset the error-situation here,
> as the first (failing) PyArg_ParseTuple has set the exception
> and I don't think this second one resets it (I could be wrong --
> no direct experience of this idiom, as I strive to avoid
> typechecks whenever I can...).
>
> Another issue is that "i" also accepts and silently truncates
> floats, which may or may not be the right thing to do (it's
> sure quite different from checking the type of the object
> for equality to integer-type:-).
>
> >   } else {
> >     return NULL;
>
> And here I think the error message would only mention
> needing a string argument, so you probably want to
> substitute for it one mentioning both string and int.
>
> >   }
> > }
>
> Alex




More information about the Python-list mailing list