pythonpython-3.xzodb

What is the correct way to use objects as keys in a ZOBD OOBTree?


In ZOBD (in Python 3.x) I would like to be able to store objects as keys in an BTrees.OOBTree.OOBTree(). Example of the error I get when I try (see the comment):

from BTrees.OOBTree import OOBTree as Btree

class Test:
    pass

bt=Btree()
t=Test()
bt[t]=None #TypeError: Object has default comparison

So, I read somewhere that __eq__ may need to be defined to remove that error, but although that seemed to fix the previous problem it seems to cause more problems. Example:

[EDIT: It should be noted that I've found some problems with inheriting OOBTree (and TreeSet) as I do here. Apparently, they don't save properly; so, it's not the same as inheriting Persistent, even though they inherit Persistent.]

from BTrees.OOBTree import OOBTree as Btree

class Test:
    def __eq__(self, other): #Maybe this isn't the way to define the method
        return self==other

bt=Btree()
t=Test()
bt[t]=None

t in bt #TypeError: unorderable types: Test() < Test()

What is the correct way to use objects as keys in a BTree or OOBTree? I do need to test whether the key exists, too.

For those who don't know, BTrees in ZODB are pretty much like scalable Python dictionaries (they should be workable with more key-value pairs than a regular Python dictionary) designed for persistence.


Solution

  • I think this answer can help with your problem.

    Bascically, you have to reimplent three methods on your object:

    1. __eq__ (equality check)
    2. __ne__ (non equality check)
    3. __hash__ to make the object really serializable as a dictionary key