1

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.

Morgan
  • 589
  • 9
  • 20

1 Answers1

3

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.

Community
  • 1
  • 1
Tom Dalton
  • 6,122
  • 24
  • 35
  • 1
    This is correct. You can see the objects are not the same by printing `obj` and `list(test.values())[1]` - it will be the same class, but different id, because they're two different copies. – viraptor Jan 26 '16 at 00:41
  • @Tom Dalton Thank you for your answer ! I never used `__eq__` so I will immediately investigate a little on its utilisation :) – Morgan Jan 26 '16 at 00:51