[ZODB-Dev] Persistent unhashable?

Greg Ward gward@mems-exchange.org
Thu, 5 Jul 2001 08:24:16 -0400


[Christian]
> Does this mean I'll need to add this object to a catalog temporarily so it
> gets an oid? Ugh! That's rather awful.

It doesn't have to be a catalog -- any existing database object should
do.  (I think that if it inherits from Persistent and its _p_oid is set,
it qualifies as an "existing database object".)

> I could also raise an unhashable error, I suppose. Is self._p_oid set to 0
> or None when the object has none, or is it just missing from the __dict__?

Neither, really: _p_oid (along with the other magical ZODB attributes)
never actually appears in an object's __dict__.  (Seems sensible to me,
since they are magical.)  However, I have never seen an AttributeError
from accessing _p_oid on a Persistent object -- so presumably the
persistence machinery either supplies None (for objects not yet "in the
database") or an 8-byte string (for objects with an OID).

> Are there any caveats in implementing an intermediary class like this?
> What do I need to upcall? For the while, I'm building a class like:
> 
> class Persistent(Persistence.Persistent):
>         def __init__(self):
>                 Persistence.Persistent.__init__(self)
> 
>         def __hash__(self):
>                 generate_hash()
> 
> Will this work? Almost? :-)

Here is our intermediary class that all persistent classes must derive
from (docstrings and comments removed):

class MXPersistent (MXBase, Persistent):
    def __hash__ (self):
        if self._p_oid:
            return hash(self._p_oid)
        else:
            return RuntimeError, "unhashable object -- no _p_oid assigned yet"

Note that your overridden constructor is unnecessary -- if all a
constructor does is call its superclass constructor, there's no point:
that's what Python would do for you if it doesn't find a constructor.
(Besides, I don't recall seeing any requirement in the ZODB docs
[ie. Jim's paper for IPC8] that Persistent-derived classes have to call
Persistent.__init__.)

        Greg
-- 
Greg Ward - software developer                gward@mems-exchange.org
MEMS Exchange                            http://www.mems-exchange.org