xrange not hashable - why not?

Gerrit Holl gerrit at nl.linux.org
Sun Jan 25 09:47:24 EST 2004


Hi,

why is an xrange object not hashable?
I was trying to do something like:

comments = {
    xrange(0, 4): "Few",
    xrange(4, 10): "Several",
    xrange(10, 100): "A lot",
    xrange(100, sys.maxint): "Can't count them"}
for (k, v) in comments.items():
    if n in k:
        commentaar = v
        break

Because:
    - I found it easier to extend than:
          if 0 <= n < 4: return "few"
          elif ... # etc
    - And better readable than:
          if k[0] <= n < k[1]: # using tuples
    - And much more memory efficient than tuple(...) (especially the
      last one ;-)
   
It would not be difficult to let xrange have a hash:

    hash((self.start, self.step, self.stop))

would be sufficient, I think.

Hmm, start, step and stop appear to have disappeared in Python 2.3...
certainly makes it somewhat more difficult. I shouldn't even to containment
testing according to PEP 260, and Python 2.3.3 should warn me not to
do... it doesn't, however.

So, should I use one of the alternatives after all? Or does someone have
something better to offer?

yours,
Gerrit.




More information about the Python-list mailing list