简体   繁体   中英

Python *list* "in" operator: equality, hash checking, or identity?

Those in the comments have asked me to provide my actual code, so I've removed the old example.

I'm making this , and I want two Page s with equal titles to compare equal. I've done this to the Page class:

def __eq__(self, other):
    return self.title == other.title

but if I do this, it isn't True:

>>> import mw_api_client as mwc
>>> w = mwc.Wiki('https://en.wikipedia.org/w/api.php')
>>> a = [w.page(str(i)) for i in range(20)]
>>> w.page('0') in a
False

How can I make this True?

The __contains __ method for lists is documented in the 'membership tests` section here:

https://docs.python.org/3.6/reference/expressions.html#membership-test-details

For container types such as list, tuple, set, frozenset, dict, or collections.deque, the expression x in y is equivalent to any(x is e or x == e for e in y) .

For your specific use case, you need to override __contains__ - however you can't just override __contains__ on the list - eg:

a = []
a.__contains__ = lambda: True
AttributeError: 'list' object attribute '__contains__' is read-only

The solution therefore is to create a custom class that wraps the list, and provides it's own __contains__ method. Something like the following (note I'm using dicts, hence obj['title'] rather than obj.title in this example - you might also want to test more things in __contains__ such as type comparison etc). I'm using UserList here since it provides a nice list class to inherit from, and makes the list contents available in data :

from collections import UserList

class MyList(UserList):
    def __init__(self, lst):
        self.data = lst

    def __contains__(self, obj):
        """Return True if any item in the list has a title, and the title matches that of the passed-in dict"""
        return any(obj['title'] == x['title'] for x in self.data if 'title' in x)

mr = {"title": "mr"}
mrs = {"title": "mrs"}
dr = {"title": "dr"}
random = {"foo": "bar"}


x = [mr, mrs, random]

y = MyList(x)

print(mr in y) # True
print(dr in y) # False
y.append(dr)
print(dr in y) # True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM