[issue28685] Optimizing list.sort() by performing safety checks in advance

Elliot Gorokhovsky report at bugs.python.org
Fri Mar 10 23:07:08 EST 2017


Elliot Gorokhovsky added the comment:

Actually, I just ran this in the patched interpreter, and it worked!
It printed:
zebra
gizmo
zebra
gizmo
zebra
gizmo
zebra
gizmo
zebra
gizmo
zebra
gizmo
zebra
gizmo

Inspired by the above result, I ran your counterexample (below) to see if
it would work as well:
from random import *
class ClassAssignmentCanBreakChecks():
    def __init__(self, i):
        self._i = i
    def __lt__ (self, other):
        print('gizmo')
        last.__class__ = OrdinaryOldInteger
        return self._i < (other._i if hasattr(other, '_i') else other)

class OrdinaryOldInteger:
    def __init__(self, i):
        self._i = i
    def __lt__(self, other):
        print('rocket')
        return self._i < (other._i if hasattr(other, '_i') else other)
lst = [ClassAssignmentCanBreakChecks(i) for i in range(10)]
shuffle(lst)
last = lst[-1]
lst.sort()

And it did! It printed:
gizmo
gizmo
gizmo
gizmo
gizmo
gizmo
gizmo
gizmo
gizmo
gizmo
gizmo
gizmo
gizmo
gizmo
gizmo
gizmo
gizmo
gizmo
gizmo
rocket
rocket
rocket

Note the "rocket" prints at the end; those could not have printed if the
compare method didn't change!

Do I have any idea *why* these tests work? No. But I swear, I *just*
re-made the patched interpeter in the directory where I ran the tests. You
will definitely be able to reproduce my results on your system.

Wacky! (seriously though I have no idea *why* this works, it just...
does... I'm scared...)

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue28685>
_______________________________________


More information about the Python-bugs-list mailing list