Can't this code: class Sequence(Sized, Iterable, Container): # ... def __contains__(self, value): for v in self: if v == value: return True return False Be shortened into this: class Sequence(Sized, Iterable, Container): # ... def __contains__(self, value): return any(item == value for value in self) Which can even fit on one line with a lambda: class Sequence(Sized, Iterable, Container): # ... __contains__ = lambda self: any(item == value for value in self)
This is slower. >>> import timeit >>> class A(list): ... def __contains__(self, value): ... for v in self: ... if v == value: ... return True ... return False ... >>> timeit.timeit('500 in x', setup='from __main__ import A; x = A(range(1000))', number=10000) 1.1222619999971357 >>> class B(list): ... def __contains__(self, value): ... return any(v == value for v in self) ... >>> timeit.timeit('500 in x', setup='from __main__ import B; x = B(range(1000))', number=10000) 2.05952100000286
Thanks for the clarification. Oh well, sad to see the more verbose code win, but I guess that's life. I tried on PyPy but the difference was even more pronounced, 0.008922450399566156 for the long version and 0.042124665810088044 for the short version.