Making an object x such that “x in [x]” returns False

前端 未结 2 1090
攒了一身酷
攒了一身酷 2020-12-09 09:09

If we make a pathological potato like this:

>>> class Potato:
...     def __eq__(self, other):
...         return False
...     def __hash__(self):
         


        
2条回答
  •  独厮守ぢ
    2020-12-09 09:44

    list, tuple, etc., does indeed do an identity check before an equality check, and this behavior is motivated by these invariants:

    assert a in [a]
    assert a in (a,)
    assert [a].count(a) == 1
    for a in container:
        assert a in container    # this should ALWAYS be true
    

    Unfortunately, dicts, sets, and friends operate by hashes, so if you mess with those you can indeed effectively break them.

    See this issue and this issue for some history.

提交回复
热议问题