views:

45

answers:

1

I'm using the Python libraries for Google App Engine. How can I override the equals() method on a class so that it judges equality on the user_id field of the following class:

class UserAccount(db.Model):
    # compare all equality tests on user_id
    user = db.UserProperty(required=True)
    user_id = db.StringProperty(required=True)
    first_name = db.StringProperty()
    last_name = db.StringProperty()
    notifications = db.ListProperty(db.Key)

Right now, I'm doing equalty by getting a UserAccount object and doing user1.user_id == user2.user_id. Is there a way I can override it so that 'user1 == user2' will look at only the 'user_id' fields?

Thanks in advance

+5  A: 

Override operators __eq__ (==) and __ne__ (!=)

e.g.

class UserAccount(db.Model):

    def __eq__(self, other):
        if isinstance(other, UserAccount):
            return self.user_id == other.user_id
        return NotImplemented

    def __ne__(self, other):
        result = self.__eq__(other)
        if result is NotImplemented:
            return result
        return not result
Anurag Uniyal
You shouldn't need to override __ne__ - the default implementation, IIRC, calls __eq__. Also, returning an exception class from a call to a builtin method? WTF? Raise it!
Nick Johnson
@Nick Johnson, sorry but you are WRONG in both cases, NotImplemented is not exception read http://docs.python.org/library/constants.html#NotImplemented and try removing `__ne__` and `print UserAccount() == UserAccount(), UserAccount() != UserAccount()` prints `True True` :)
Anurag Uniyal
@Nick Johnson, also http://stackoverflow.com/questions/878943/why-return-notimplmented-instead-of-raising-notimplementederror explains why NotImplemented instead of NotImplementedError
Anurag Uniyal
Apologies. You're totally right on both counts, and I'm wrong. At least I learned something new! :)
Nick Johnson
Thanks both you guys, you've been a big help.
Cuga