implementing __hash__ in mapped classes

278 views
Skip to first unread message

Victor Olex

unread,
Sep 20, 2010, 3:37:09 PM9/20/10
to sqlalchemy
What is a good practice for implementing __hash__ method in mapped
classes? Left unimplemented an object id is returned. Within the same
session SQLAlchemy ensures that the same record is mapped to one
instance of the mapped class. However if object is not in session
(expunged or session closed) and the same record gets retrieved from
another session its identities will be different. It would make sense
to return hash of primary key if object is persisted in database.

Are there any gotchas in doing the following (assume id field is whole
primary key):

def __hash__(self):
return id(self) if self.id is None else hash(self.id)

Can you also comment in context of

Michael Bayer

unread,
Sep 20, 2010, 3:47:11 PM9/20/10
to sqlal...@googlegroups.com
SQLalchemy goes through a lot of effort to ensure that its own identity map and other related functions are using object identity as referenced by the python "is" operator as well as the id() function. You are free to implement any kind of __hash__() method, as well as a custom __nonzero__(), and the operation of the ORM will remain unaffected.

> --
> You received this message because you are subscribed to the Google Groups "sqlalchemy" group.
> To post to this group, send email to sqlal...@googlegroups.com.
> To unsubscribe from this group, send email to sqlalchemy+...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/sqlalchemy?hl=en.
>

Reply all
Reply to author
Forward
0 new messages