Records and Value Equality
Lesson 41 of 48 in Coddy's Python for C# Developers course.
Implement value equality without confusing it with identity.
C# reference excerpt
Executable statements use C# top-level program style; type-only examples are declarations. System names assume the usual using System directive.
var a = new Point(2, 3);
var b = new Point(2, 3);
Console.WriteLine(a == b);
Console.WriteLine(object.ReferenceEquals(a, b));
record Point(int X, int Y);Python
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
a = Point(2, 3)
b = Point(2, 3)
print(a == b)
print(a is b)What changes
A C# record class and this Python dataclass generate value-oriented equality, while the separately created instances retain distinct identity. Plain Python classes use identity-based equality by default unless customized. @dataclass also generates initialization and a useful representation; it does not make these instances immutable or enforce annotations. For a custom __eq__, return NotImplemented for unsupported types so Python can try the other comparison.
Transfer mistake
NotImplemented is a special return value, not the NotImplementedError exception. Generated dataclass equality requires the same concrete type; the task explicitly requests an isinstance-based Coordinate comparison instead.
Your task
Implement Coordinate(x, y) storing integer coordinates and a custom __eq__. For isinstance(other, Coordinate), compare both coordinates and return bool; for other types return NotImplemented. The driver reads two integer pairs, creates separate objects, prints equality and identity, changes the second y, and prints equality again and equality against None. It also prints whether a direct __eq__(None) returned NotImplemented; that last line must be True.
Challenge
BeginnerImplement Coordinate(x, y) storing integer coordinates and a custom __eq__. For isinstance(other, Coordinate), compare both coordinates and return bool; for other types return NotImplemented. The driver reads two integer pairs, creates separate objects, prints equality and identity, changes the second y, and prints equality again and equality against None. It also prints whether a direct __eq__(None) returned NotImplemented; that last line must be True.
Editable implementation files: coordinate.py. The locked driver.py is the supplied launcher or input/output harness and must remain unchanged.
Keep the supplied imports and exact API names. Return results or raise the required exceptions; do not read input or print from these implementation 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
1C# Foundations in Python
Run the Python WorkspaceOutput, Strings, and CommentsTyped Locals to Python NamesDivision and RemaindersIndentation Instead of BracesRecap: Port a Receipt4Loops and Transformations
From foreach to forIndexes and Dictionary ItemsSentinels and Loop ControlFrom LINQ to ComprehensionsRecap: Stable Ranking2None and Decisions
Nullable Values and NoneEquality, Identity, and TypesTruth Tests and FallbacksBranch PriorityRecap: Eligibility Rules5Functions and Scope
Define Functions and ReturnNamed Arguments and DefaultsStar Arguments and UnpackingCallbacks and Python ScopeRecap: Pricing Functions8Composition and Inheritance
Replaceable CollaboratorsOverrides and superInterfaces and Duck TypingRecords and Value EqualityRecap: Dispatch by Behavior3Collections and References
From List<T> to listTuples and UnpackingDictionary Keys and ValuesSets, Aliases, and CopiesRecap: Stock Lookup6Reliable Python Programs
Input and Exact OutputExceptions and ValidationImports and the Main GuardType Hints and Runtime TypesRecap: Validate a Batch9Project: Order Processor
Project 1: Order ModelProject 2: Pricing PoliciesPractice on your own: Online Python compiler