Difference of hash and __hash__()
Jeff Epler
jepler at unpythonic.net
Fri Sep 5 10:39:31 EDT 2003
On Wed, Sep 03, 2003 at 08:38:12AM -0700, Michael Chermside wrote:
> So submit the bugreport, but I'm guessing that slices will remain
> unhashable. IIRC, Guido felt that the risk of confusion (folks
> thinking that {}[1:2] would return some part or subset of the dict)
> was greater than the utility of using slices as keys in a dict
One interpretation of dict slicing:
def slice_dict(d, s):
ret = {}
if s.stop > s.start:
if s.step is None:
for k, v in d.iteritems():
if k >= s.start and k < s.stop:
ret[k] = v
else:
for k, v in d.iteritems():
if k >= s.start and k < s.stop and ((k-s.start) % s.step) == 0:
ret[k] = v
else:
raise NotImplementedError("lazy")
return ret
>>> d = dict([(x, None) for x in range(20)])
>>> l = range(20)
>>> print slice_dict(d, slice(3,7)).keys(), l[3:7]
[3, 4, 5, 6] [3, 4, 5, 6]
>>> print slice_dict(d, slice(3,7,2)).keys(), l[3:7:2]
[3, 5] [3, 5]
>>> d = dict([(x, None) for x in string.lowercase])
>>> slice_dict(d, slice('d', 'p')).keys()
['e', 'd', 'g', 'f', 'i', 'h', 'k', 'j', 'm', 'l', 'o', 'n']
On Wed, Sep 03, 2003 at 08:38:12AM -0700, Michael Chermside wrote:
> (for which, I believe, he was unable to come up with a single
> plausible use case).
One use of slices as dict keys (memoized slicing of a user type):
class SliceIndexCache:
def __init__(self):
self._cache = None
def compute_slice(self, sl): raise NotImplementedError
def compute_index(self): raise NotImplementedError
def __getitem__(self, i):
if not self._cache.has_key(i):
if isinstance(i, slice):
self._cache[i] = compute_slice(i)
else:
self._cache[i] = compute_index(i)
return self._cache[i]
More information about the Python-list
mailing list