0

I need to compare current and candidate values for a property, keep what's equal, remove what's different and add absent ones. I wrote the following function but it looks way more complicated than it should be:

def check_and_update_claim(new_claims, item_page, ignore_refs):
    prop = new_claims[0].getID()
    if prop in item_page.get()["claims"].keys():
        for current_claim in item_page.claims[prop]:
            different = []
            same = []
            for new_claim in new_claims:
                if not new_claim.same_as(current_claim, ignore_refs=ignore_refs):
                    different.append(True)
                else:
                    different.append(False)
                    same.append(new_claim)
            if all(different):
                with warnings.catch_warnings():
                    warnings.simplefilter("ignore")
                    item_page.removeClaims(current_claim, summary=u"Removing to update value")
            if same:
                for new_claim in same:
                    new_claims.remove(new_claim)
    for new_claim in new_claims:
        if new_claim.getTarget():
            item_page.addClaim(new_claim, summary="Adding or updating value")

Is there a better way of doing this? I can't create sets of Claim objects, which I guess would facilitate checking for unique values and differences between current and candidates.

Martim Passos
  • 137
  • 1
  • 12
  • can you share the objects too? you could also define `__eq__` in the objects – Axeltherabbit Oct 28 '22 at 15:22
  • so, I did try to follow [this](https://stackoverflow.com/questions/43504568/compare-dictionaries-with-unhashable-or-uncomparable-values-e-g-lists-or-data) since the objects provide a same_as() method (as seen in my example). But I still couldn't create a set of `ClaimWrapper` objects, maybe I did something wrong – Martim Passos Oct 28 '22 at 15:23
  • Here's the [docs](https://doc.wikimedia.org/pywikibot/master/api_ref/pywikibot.html#pywikibot.Claim) for the object – Martim Passos Oct 28 '22 at 15:24
  • Wrap your unhashable type in a class and add a __hash__() special method. Take some data in the class instance that you decide to be unique and use that to calculate the __hash__() return value (which should be an integer) You can use the system function hash() to do that or any other hash from a library such as hashlib. – Jay M Oct 28 '22 at 15:47

0 Answers0