I want to override __cmp__
, __eq__
, and __hash__
so I can do set operations on a SQLAlchemy Declarative Base model. Will this cause any conflicts with the Declarative Base Implementation?
Asked
Active
Viewed 3,165 times
12
2 Answers
7
Maybe, depending on the comparison function implementation.
You have to be careful when using __eq__
or __cmp__
for comparing with the other
object, because SQLAlchemy may compare your object with some symbols such as NEVER_SET
which don't have the same type. Take a look at this SQLAlchemy method:
def get_all_pending(self, state, dict_):
if self.key in dict_:
current = dict_[self.key]
if current is not None:
ret = [(instance_state(current), current)]
else:
ret = [(None, None)]
if self.key in state.committed_state:
original = state.committed_state[self.key]
if original not in (NEVER_SET, PASSIVE_NO_RESULT, None) and \
original is not current:
ret.append((instance_state(original), original))
return ret
else:
return []
The original not in (NEVER_SET, PASSIVE_NO_RESULT, None)
line may raise an error if the comparison doesn't check for the equality of the types first, or for the existence of the fields that are used in the comparison
As a solution, you should take differing types into account.
Also avoid overriding __cmp__
and use rich comparison operators instead.
-
Good catch! This is important. – Matthew Moisen Jun 25 '16 at 20:27
2
no. It'll work just fine.

nosklo
- 217,122
- 57
- 293
- 297
-
4Can you cite any SQLAlchemy documentation that suggests that this would be ok? – DuneBug Apr 03 '13 at 23:50
-
1@DuneBug I can't see why it would be a problem. Sqlalchemy itself doesn't override those special methods for the declarative base. – nosklo Apr 08 '13 at 17:54
-
1If SQLAlchemy ever uses __eq__ like @ovidiu mentions, it could be an issue. – Matthew Moisen Jun 25 '16 at 20:28