Equality Beyond operator==
Lesson 41 of 48 in Coddy's Python for C++ Developers course.
An ordinary Python class inherits identity-based equality unless it defines __eq__. A dataclass can generate initialization, representation, and field equality from annotated fields. C++17 structs do not automatically gain fieldwise operator==; the example defines it explicitly. Python dataclasses remain mutable by default and are not tuple-like frozen records. Return NotImplemented from __eq__ for unsupported operand types so Python can try the other operand behavior.
C++17 excerpt: inside main
Standard-library headers are supplied in the runnable companion program.
struct Tag {
std::string text;
bool operator==(const Tag& other) const { return text == other.text; }
};
Tag a{"x"}, b{"x"};
std::cout << std::boolalpha << (a == b) << ' ' << (&a == &b) << '\n';
b.text = "y";
std::cout << (a == b) << '\n';Python
from dataclasses import dataclass
@dataclass
class Tag:
text: str
a, b = Tag("x"), Tag("x")
print(a == b, a is b)
b.text = "y"
print(a == b)Porting trap
NotImplemented is a sentinel return value, not the NotImplementedError exception. Mutable value-equal dataclasses are normally unhashable, so do not assume they are safe dict keys.
Implement the task below in its editable Python modules. The locked driver.py supplies execution and checks. Keep the specified imports and API names.
Challenge
BeginnerImplement Coordinate(x, y) with value equality: __eq__(other) compares both stored integer coordinates when other is a Coordinate; otherwise return NotImplemented. Input has two lines, each containing two integers. The driver creates two independent coordinates, prints their equality and identity, increments the second coordinate's y, prints equality again, and finally compares the first coordinate with None. Use isinstance(other, Coordinate) before accessing the other coordinates. Return booleans from the supported comparison, not strings.
The locked driver handles input and output. Submit only the required class and function definitions with the exact API names. Do not read input or print from your classes.
The driver also calls a.__eq__(None) directly and prints whether the result is NotImplemented; the final line must be True.
Your code goes in the editable files coordinate.py. driver.py holds the supplied input/output code and API checks and cannot be edited. Keep the supplied imports; do not read input or print from the editable modules.
Try it yourself
from coordinate import Coordinate
x, y = [int(v) for v in input().split()]
a = Coordinate(x, y)
x, y = [int(v) for v in input().split()]
b = Coordinate(x, y)
print(a == b)
print(a is b)
b.y += 1
print(a == b)
print(a == None)
print(a.__eq__(None) is NotImplemented)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for C++ Developers
1From C++ to Python
Run Your First Python ProgramStreams to printNames, auto, and constDivision and Integer RangeBlocks and Name ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Range Loops and RebindingEntries and enumerateLoop Control Without ++Algorithms and ComprehensionsRecap: Build a Ranking2Values and Decisions
None, nullptr, and boolValues, Addresses, IdentityTruth Tests and OperandsBranches and Value SelectionRecap: Eligibility Rules5Functions, Calls, and Closures
Functions and Shared ObjectsDefaults and Named ArgumentsPacking and Unpacking CallsClosures and Capture TimingRecap: Refactor a Pricing Tool8Composition and Dispatch
Composition Without Value CopyInheritance and Method LookupVirtual Calls and Duck TypingEquality Beyond operator==Recap: Notification Channels3STL Habits and Python Objects
From vector to listTuples and Structured BindingsMaps, Keys, and OrderingValue Copies and Shared ListsRecap: Clean an Inventory6Errors, Resources, and Modules
Text Input and Exact OutputExceptions and RAIIModules Instead of HeadersHints Are Not Static TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler