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?
no. It'll work just fine.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With