[issue1766304] improve xrange.__contains__

Mark Dickinson report at bugs.python.org
Thu Sep 3 12:03:18 CEST 2009

Mark Dickinson <dickinsm at gmail.com> added the comment:

The trunk patch is also unacceptable in its current form:

 1. there are no docs or tests
 2. keyval, start, step and end should have type long, not type int
    (as Antoine already mentioned)
 3. the expression ((keyval - start) % step) can overflow, leading to
    undefined behaviour (e.g., wrong results, segfaults, strange
    effects from gcc optimizations that assume no overflow).  For
    example, with the patch, on Linux/x86-64, I get:

      >>> x = xrange(-2000000000, 2000000000, 5)
      >>> 1000000000 in x

    This should be relatively easy to fix:  e.g., if you already
    know that step > 0 and start <= keyval and keyval < stop, then
    '(unsigned long)keyval - (unsigned long)start'  is safe from

 4. the containment check only works for ints:  with the patch, I get:

      >>> x = xrange(10)
      >>> 4 in x
      >>> 4L in x
      >>> 4.0 in x

    but without the patch applied, all these return True.  It's possible
    that it's worth special-casing integer inputs for the sake of
    speed, but I don't think the behaviour should change like this for
    other types.


Python tracker <report at bugs.python.org>

More information about the Python-bugs-list mailing list