[Python-Dev] Re: d = {}; d[0:1] = 1; d[0:1] = 2; print d[:]

Thomas Wouters thomas@xs4all.net
Thu, 1 Mar 2001 23:21:07 +0100


On Thu, Mar 01, 2001 at 04:01:52PM -0500, Guido van Rossum wrote:
> > Quoth Robin Thomas <robin.thomas@starmedia.net>:

[ Dicts accept slice objects as keys in assignment, but not in retrieval ]

> > | 1) Is this behavior considered a bug by the BDFL or the community at large?

> I can't speak for the community, but it smells like a bug to me.

Speaking for the person who implemented the slice-fallback to sliceobjects:
yes, it's a bug, because it's an unintended consequence of the change :) The
intention was to eradicate the silly discrepancy between indexing, normal
slices and extended slices: normal indexing works through __getitem__,
sq_item and mp_subscript. Normal (two argument) slices work through
__getslice__ and sq_slice. Extended slices work through __getitem__, sq_item
and mp_subscript again.

Note, however, that though *this* particular bug is new in Python 2.0, it
wasn't actually absent in 1.5.2 either!

Python 1.5.2 (#0, Feb 20 2001, 23:57:58)  [GCC 2.95.3 20010125 (prerelease)]
on linux2
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> d = {}
>>> d[0:1] = "spam"
Traceback (innermost last):
  File "<stdin>", line 1, in ?
TypeError: object doesn't support slice assignment
>>> d[0:1:1] = "spam"
>>> d[0:1:] = "spam"
>>> d
{slice(0, 1, None): 'spam', slice(0, 1, 1): 'spam'}

The bug is just extended to cover normal slices as well, because the absense
of sq_slice now causes Python to fall back to normal item setting/retrieval.

I think making slices hashable objects makes the most sense. They can just
be treated as a three-tuple of the values in the slice, or some such.
Falling back to just sq_item/__getitem__ and not mp_subscript might make
some sense, but it seems a bit of an artificial split, since classes that
pretend to be mappings would be treated differently than types that pretend
to be mappings.

-- 
Thomas Wouters <thomas@xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!