C api question and determining PyObject type

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon Nov 16 17:03:16 CET 2009


En Mon, 16 Nov 2009 07:44:34 -0300, lallous <lallous at lgwm.org> escribió:

> Actually, the object class is defined as:
>     class __object(object):
>         def __getitem__(self, idx):
>             return getattr(self, idx)
>
> Anyway, now I check like this:
>
> bool PyIsSequenceType(PyObject *obj)
> {
>   if (!PySequence_Check(obj))
>     return false;
>   Py_ssize_t sz = PySequence_Size(obj);
>   if (sz == -1 || PyErr_Occurred() != NULL)
>   {
>     PyErr_Clear();
>     return false;
>   }
>   return true;
> }
>
> I don't like it, any other suggestions?

Yes: find another name for the "thing" you're checking for. It's not the  
same as a "sequence" in the Python sense.

Perhaps you want to consider your type a mapping? Sequences and mappings  
have a lot in common (mappings have length too.) In C you have separate  
slots tp_as_sequence, tp_as_mapping; but in Python code, __getitem__ is  
used for both meanings (and goes into both set of pointers.) tp_as_mapping  
takes precedence over tp_as_sequence.

-- 
Gabriel Genellina




More information about the Python-list mailing list