Skip to content

Instantly share code, notes, and snippets.

@carsonip
Created November 22, 2019 06:04
Show Gist options
  • Save carsonip/b8d7c8febd5f5b7bfe930243e713c708 to your computer and use it in GitHub Desktop.
Save carsonip/b8d7c8febd5f5b7bfe930243e713c708 to your computer and use it in GitHub Desktop.
Useful Python Snippets

Equality of Python classes using slots

import operator

class CommonEqualityMixin(object):

    __slots__ = ()

    def __eq__(self, other):
        if isinstance(other, self.__class__):
            if self.__slots__ == other.__slots__:
                 attr_getters = [operator.attrgetter(attr) for attr in self.__slots__]
                 return all(getter(self) == getter(other) for getter in attr_getters)

        return False

    def __ne__(self, other):
        return not self.__eq__(other)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment