[Python-Dev] Prospective Peephole Transformation
Jim Jewett
jimjjewett at gmail.com
Fri Feb 18 20:10:05 CET 2005
Raymond Hettinger:
> tried transforming the likes of "x in (1,2,3)" into "x in frozenset([1,2,3])".
>... There were substantial savings even if the set contained only a
single entry.
>... where x was non-hashable and it would raise a TypeError instead of
> returning False as it should.
I read the objection as saying that it should not return False, because
an unhashable object might pretend it is equal to a hashable one in the set.
"""
class Searchset(frozenset):
def __contains__(self, element):
try:
return frozenset.__contains__(self, element)
except TypeError:
return False
"""
So instead of
return False
it should be
return x in frozenset.__iter__()
This would be a net loss if there were many unhashable x. You could restrict
the iteration to x that implement a custom __eq__, if you ensured that none
of the SearchSet elements do... but it starts to get uglier and less general.
Raymond has already look at http://www.python.org/sf/1141428, which
contains some test case patches to enforce this implicit
"sequences always use __eq__; only mappings can short-circuit on __hash__"
contract.
-jJ
More information about the Python-Dev
mailing list