eliben at gmail
Mar 3, 2012, 12:36 AM
slice subscripts for sequences and mappings
I find a strange discrepancy in Python with regards to slice
subscripting of objects, at the C API level. I mean things like
I'd expect slice subscripts to be part of the sequence interface, and
yet they are not. In fact, they are part of the mapping interface. For
example, the list object has its slice get/set methods assigned to a
PyMappingMethods struct. So does a bytes object, and pretty much every
other object that wants to support subscripts.
This doesn't align well with the documentation, in at least two places.
1) The library documentation
(http://docs.python.org/dev/library/stdtypes.html) in 4.8 says:
"Mappings are mutable objects. There is currently only one
standard mapping type, the dictionary"
Why then does a list implement the mapping interface? Moreover, why
does bytes, an immutable object, implement the mapping interface?
2) The same documentation page in 4.6 says, in the operation table:
s[i:j] slice of s from i to j
s[i:j:k] slice of s from i to j with step k
But in the implementation, the slice subscripts are part of the
mapping, not the sequence inteface.
The PySequenceMethods structure does have fields for slice accessors,
but their naming (was_sq_slice, was_sq_ass_slice) suggests they're
just deprecated placeholders.
This also doesn't align well with logic, since mappings like dict have
no real meaning for slice subscripts. These logically belong to a
sequence. Moreover, it takes subscripts for single a single numeric
index away from subscripts for a slice into a different protocol (the
former in sequence, the latter in mapping).
I realize I must be missing some piece of the history here and not
suggesting to change anything. I do think that the documentation,
especially in the area of the type object that defines the sequence
and mapping protocols, could be clarified to express what is expected
of a new type that wants to act as a sequence. In particular, it
should be said explicitly that such a type must implement the mapping
protocol if it wants slice subscripting.
If this makes any sense at all, I will open an issue.
Python-Dev mailing list
Python-Dev [at] python