12

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?

nosklo
  • 217,122
  • 57
  • 293
  • 297
eldermao
  • 633
  • 8
  • 18

2 Answers2

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.

Community
  • 1
  • 1
Ovidiu S.
  • 320
  • 3
  • 6
2

no. It'll work just fine.

nosklo
  • 217,122
  • 57
  • 293
  • 297