Search code examples
pythonshelve

Check if an object is in a shelve


I would like to know if there is a clean way to check if a shelve contain an object. As you will see in the example, we can't do it like with a dictionary (myObj in list(myDictionary.values())). That writing will work if I search a builtin object (str, int...) but won't work if I search something else.

import shelve

class foo():
    def __init__(self):
        pass

obj = foo()

test = shelve.open('test')

test["elmt1"] = 1
test['elmt2'] = obj

test.update()

print(1 in list(test.values())) # Result is True
print(obj in list(test.values())) # Result is False

If there isn't any simple solution I can obviously work only with a copy of the shelve and replace the shelve by my copy at the end of my script.


Solution

  • Define the __eq__ on your foo class and it will work. Obviously, you'll need to work out what equality means between two instances of the same class, which has no attributes...

    E.g. In this case, all Foo instances compare equal, so your code above will print True for both cases.

    class Foo(object):
        def __init__(self):
            pass
        def __eq__(self, other):
            return isinstance(other, Foo)
    

    Also, as good practice, all your classes should inherit from object - see Python class inherits object and What is the difference between old style and new style classes in Python? for more info.