PySequence_Check is always true on instances?
Tim Peters
tim.one at comcast.net
Fri Mar 22 16:51:30 EST 2002
[Walter Moreira]
> Hi. If I define a simple class
>
> >>> class eggs:
> ... pass
> >>> a = eggs()
>
> and I call PySequence_Check on the instance 'a', at C level, it
> returns 1.
Right. This is an unfortunate consequence of the "type/class split" before
2.2: all classic classes fill in all type method slots "just in case", so
pass all tests that just look for the existence of non-NULL method slots:
int
PySequence_Check(PyObject *s)
{
return s != NULL && s->ob_type->tp_as_sequence &&
s->ob_type->tp_as_sequence->sq_item != NULL;
}
> If the class is a new style class:
>
> >>> class eggs(object):
> ... pass
> >>> b = eggs()
>
> then PySequence_Check on 'b' returns 0. I proved this on Python
> 2.2 and 2.1 (couldn't download 2.2.1 yet).
That won't change in 2.2.1.
All old-style instances return true for these; whether a new-style instance
returns true depends on whether it inherits or directly defines the type
slots being examined.
> Is this a bug?
Not in the sense you're hoping for <wink>.
> If it is not a bug, which is the standard way to check that an
> object is sequence, in C?
There isn't one: it depends on exactly what *you* mean by "a sequence".
It's a fuzzy concept in Python, and you'll find that PySequence_Check() is
rarely used in the core. In most cases for 2.2, it's not a question worth
even trying to answer: most "sequence contexts" in 2.2 were generalized to
allow any iterable object, and the core usually determines whether an object
is iterable by seeing whether PyObject_GetIter() returns NULL or not.
More information about the Python-list
mailing list