[Python-Dev] Prospective Peephole Transformation

Raymond Hettinger raymond.hettinger at verizon.net
Fri Feb 18 07:53:37 CET 2005

Based on some ideas from Skip, I had tried transforming the likes of "x
in (1,2,3)" into "x in frozenset([1,2,3])".  When applicable, it
substantially simplified the generated code and converted the O(n)
lookup into an O(1) step.  There were substantial savings even if the
set contained only a single entry.  When disassembled, the bytecode is
not only much shorter, it is also much more readable (corresponding
almost directly to the original source).

The problem with the transformation was that it didn't handle the case
where x was non-hashable and it would raise a TypeError instead of
returning False as it should.  That situation arose once in the email
module's test suite.

To get it to work, I would have to introduce a frozenset subtype:

    class Searchset(frozenset):
        def __contains__(self, element):
                return frozenset.__contains__(self, element)
            except TypeError:
                return False

Then, the transformation would be "x in Searchset([1, 2, 3])".  Since
the new Searchset object goes in the constant table, marshal would have
to be taught how to save and restore the object.

This is a more complicated than the original frozenset version of the
patch, so I would like to get feedback on whether you guys think it is
worth it.

Raymond Hettinger

More information about the Python-Dev mailing list