Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding __cmp__, __eq__, and __hash__ for SQLAlchemy Declarative Base

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?

like image 417
eldermao Avatar asked Aug 10 '10 20:08

eldermao


2 Answers

no. It'll work just fine.

like image 71
nosklo Avatar answered Nov 04 '22 11:11

nosklo


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.

like image 45
Ovidiu S. Avatar answered Nov 04 '22 09:11

Ovidiu S.