[Python-Dev] slice subscripts for sequences and mappings

Antoine Pitrou solipsis at pitrou.net
Sat Mar 3 22:02:50 CET 2012


On Sat, 3 Mar 2012 12:59:13 -0800
Thomas Wouters <thomas at python.org> wrote:
> 
> Why even have separate tp_as_sequence and tp_as_mapping anymore? That
> particular distinction never existed for Python types, so why should it
> exist for C types at all? I forget if there was ever a real point to it,
> but all it seems to do now is create confusion, what with many sequence
> types implementing both, and PyMapping_Check() and PySequence_Check() doing
> seemingly random things to come up with somewhat sensible answers.

Ironically, most of the confusion stems from sequence types
implementing the mapping protocol for extended slicing.

> Do note
> that the dict type actually implements tp_as_sequence (in order to support
> containtment tests) and that PySequence_Check() has to explicitly return 0
> for dicts -- which means that it will give the "wrong" answer for another
> type that behaves exactly like dicts.

It seems to be a leftover:

int
PySequence_Check(PyObject *s)
{
    if (PyDict_Check(s))
        return 0;
    return s != NULL && s->ob_type->tp_as_sequence &&
        s->ob_type->tp_as_sequence->sq_item != NULL;
}

Dict objects have a NULL sq_item so even removing the explicit check
would still return the right answer.

> Getting rid of the misleading distinction seems like a much better idea
> than trying to re-conflate some of the issues.

This proposal sounds rather backwards, given that we now have separate
Mapping and Sequence ABCs.

Regards

Antoine.




More information about the Python-Dev mailing list