5.4. OOP Equality

5.4.1. Default Behavior

  • By default, all objects are not equal

>>> class User:
...     def __init__(self, firstname, lastname):
...         self.firstname = firstname
...         self.lastname = lastname
>>> a = User('Alice', 'Apricot')
>>> b = User('Alice', 'Apricot')
>>> a == b
False

5.4.2. Equality Method

  • Both object are not equal

Mind, that the following implementation of __eq__ method is erroneous and should not be used.

>>> class User:
...     def __init__(self, firstname, lastname):
...         self.firstname = firstname
...         self.lastname = lastname
...
...     def __eq__(self, other):
...         return self.firstname == other.firstname \
...            and self.lastname == other.lastname
>>> a = User('Alice', 'Apricot')
>>> b = User('Alice', 'Apricot')
>>> a == b
True

5.4.3. Equality Problem

  • Both object are not equal

Mind, that the following implementation of __eq__ method is erroneous and should not be used:

>>> class User:
...     def __init__(self, firstname, lastname):
...         self.firstname = firstname
...         self.lastname = lastname
...
...     def __eq__(self, other):
...         return self.firstname == other.firstname \
...            and self.lastname == other.lastname
>>>
>>>
>>> class Admin:
...     def __init__(self, firstname, lastname):
...         self.firstname = firstname
...         self.lastname = lastname
>>> a = User('Alice', 'Apricot')
>>> b = User('Alice', 'Apricot')
>>> c = Admin('Alice', 'Apricot')
>>> a == b
True
>>> a == c
True

5.4.4. Equality Solution

  • Both object are not equal

The following implementation of __eq__ method is correct and can be used:

>>> class User:
...     def __init__(self, firstname, lastname):
...         self.firstname = firstname
...         self.lastname = lastname
...
...     def __eq__(self, other):
...         return self.__class__ is other.__class__ \
...            and self.firstname == other.firstname \
...            and self.lastname == other.lastname
>>>
>>>
>>> class Admin:
...     def __init__(self, firstname, lastname):
...         self.firstname = firstname
...         self.lastname = lastname
>>> a = User('Alice', 'Apricot')
>>> b = User('Alice', 'Apricot')
>>> c = Admin('Alice', 'Apricot')
>>> a == b
True
>>> a == c
False

5.4.5. Dataclasses

  • By default eq=True (if not specified)

  • Objects of the same type are equal

  • Objects of different types are not equal

SetUp:

>>> from dataclasses import dataclass

By default instances of the same dataclass are equal:

>>> @dataclass
... class User:
...     firstname: str
...     lastname: str
>>>
>>> a = User('Alice', 'Apricot')
>>> b = User('Alice', 'Apricot')
>>>
>>> a == b
True

You can turn this behavior off by setting eq=False:

>>> @dataclass(eq=False)
... class User:
...     firstname: str
...     lastname: str
>>>
>>> a = User('Alice', 'Apricot')
>>> b = User('Alice', 'Apricot')
>>>
>>> a == b
False

5.4.6. Assignments

# %% About
# - Name: OOP Equality Point
# - Difficulty: easy
# - Lines: 3
# - Minutes: 3

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% English
# 1. Override operator ``==`` so that two `Point` objects are equal
# 2. Remember to check if `other` is instance of the same class
# 3. Run doctests - all must succeed

# %% Polish
# 1. Nadpisz operator ``==``, tak aby dwa obiekty `Point` były równe
# 2. Pamiętaj aby sprawdzić czy `other` jest instancją tej samej klasy
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Expected
# >>> pt1 = Point(x=1, y=2)
# >>> pt2 = Point(x=1, y=2)
# >>> pt3 = Point(x=3, y=4)
# >>>
# >>> pt1 == pt2
# True
# >>> pt1 == pt3
# False

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0

>>> assert sys.version_info >= (3, 9), \
'Python has an is invalid version; expected: `3.9` or newer.'

>>> pt1 = Point(x=1, y=2)
>>> pt2 = Point(x=1, y=2)
>>> pt3 = Point(x=3, y=4)

>>> pt1 == pt2
True

>>> pt1 == pt3
False
"""

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`

# %% Imports

# %% Types
from typing import Callable
Point: type
__eq__: Callable[[object, object], bool]

# %% Data

# %% Result
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

# %% About
# - Name: OOP Equality Group
# - Difficulty: easy
# - Lines: 3
# - Minutes: 3

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% English
# 1. Override operator ``==`` so that two `Group` objects are equal
# 2. Remember to check if `other` is instance of the same class
# 3. Run doctests - all must succeed

# %% Polish
# 1. Nadpisz operator ``==``, tak aby dwa obiekty `Group` były równe
# 2. Pamiętaj aby sprawdzić czy `other` jest instancją tej samej klasy
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Expected
# >>> users = Group(gid=1, name='users')
#
# >>> users == Group(gid=1, name='users')
# True

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0

>>> assert sys.version_info >= (3, 9), \
'Python has an is invalid version; expected: `3.9` or newer.'

>>> class Other:
...     def __init__(self, gid, name):
...         self.gid = gid
...         self.name = name

>>> Group(gid=1, name='users') == Group(gid=1, name='users')
True

>>> Group(gid=1, name='users') == Group(gid=2, name='staff')
False

>>> Group(gid=1, name='users') == Group(gid=3, name='admins')
False

>>> Group(gid=1, name='users') == Other(gid=0, name='root')
False

>>> Group(gid=1, name='users') == Other(gid=1, name='users')
False
"""

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`

# %% Imports

# %% Types
from typing import Callable
Group: type
__eq__: Callable[[object, object], bool]

# %% Data

# %% Result
class Group:
    def __init__(self, gid, name):
        self.gid = gid
        self.name = name

# %% About
# - Name: OOP Equality User
# - Difficulty: easy
# - Lines: 3
# - Minutes: 3

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% English
# 1. Override operator ``==`` so that two `User` objects are equal
# 2. Remember to check if `other` is instance of the same class
# 3. Run doctests - all must succeed

# %% Polish
# 1. Nadpisz operator ``==``, tak aby dwa obiekty `User` były równe
# 2. Pamiętaj aby sprawdzić czy `other` jest instancją tej samej klasy
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Expected
# >>> User('Alice', 'Apricot') == User('Alice', 'Apricot')
# True
#
# >>> User('Alice', 'Apricot') == User('Bob', 'Blackthorn')
# False
#
# >>> User('Alice', 'Apricot') == User('Alice', 'Blackthorn')
# False
#
# >>> User('Alice', 'Apricot') == User('Bob', 'Apricot')
# False
#
# >>> User('Alice', 'Apricot') == Admin('Alice', 'Apricot')
# False

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0

>>> assert sys.version_info >= (3, 9), \
'Python has an is invalid version; expected: `3.9` or newer.'

>>> class Admin:
...     def __init__(self, firstname, lastname):
...         self.firstname = firstname
...         self.lastname = lastname

>>> User('Alice', 'Apricot') == User('Alice', 'Apricot')
True

>>> User('Alice', 'Apricot') == User('Bob', 'Blackthorn')
False

>>> User('Alice', 'Apricot') == User('Alice', 'Blackthorn')
False

>>> User('Alice', 'Apricot') == User('Bob', 'Apricot')
False

>>> User('Alice', 'Apricot') == Admin('Alice', 'Apricot')
False
"""

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`

# %% Imports

# %% Types
from typing import Callable
User: type
__eq__: Callable[[object, object], bool]

# %% Data

# %% Result
class User:
    def __init__(self, firstname, lastname):
        self.firstname = firstname
        self.lastname = lastname