[Python-Dev] PySequence_Check but no __len__

Greg Ewing greg.ewing at canterbury.ac.nz
Fri Jun 22 19:57:15 EDT 2018


Terry Reedy wrote:
> I am surprised that a C-API function calls something a 'sequence' 
> without it having __len__.

It's a bit strange that PySequence_Check exists at all.
The principle of duck typing would suggest that one
should be checking for the specific methods one needs.

I suspect it's a holdover from very early Python, where
the notion of a "sequence type" and a "mapping type"
were more of a concrete thing. This is reflected in
the existence of the tp_as_sequence and tp_as_mapping
substructures. It was expected that a given type would
either implement all the methods in one of those
substructures or none of them, so shorcuts such as
checking for just one method and assuming the others
would exist made sense.

But user-defined classes messed all that up, because
it became possible to create a type that has __getitem__
but not __len__, etc. It also made it impossible to
distinguish reliably between a sequence and a mapping.

So it seems to me that PySequence_Check and related
functions are not very useful any more, since it's not
possible for them to really do what they claim to do.

-- 
Greg


More information about the Python-Dev mailing list