Equality and Data Classes
Lesson 41 of 48 in Coddy's Python for C Developers course.
C has no struct == operator: compare meaningful fields with an explicit function. memcmp is not a general substitute because padding bytes and representation details need not match semantic values. Python classes can implement __eq__; dataclass can generate field-based equality and initialization. The displayed dataclass is mutable by default and compares instances of the same class. The task deliberately implements equality manually with an isinstance check, which also accepts suitable subclasses.
C: complete example.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
struct Point { int x; int y; };
int equal(struct Point a, struct Point b) { return a.x == b.x && a.y == b.y; }
int main(void) {
struct Point a = {2, 3}; struct Point b = {2, 3};
printf("%d %d\n", equal(a, b), &a == &b);
return 0;
}Python: complete example.py
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
a = Point(2, 3)
b = Point(2, 3)
print(a == b, a is b)Watch the difference
Return NotImplemented from __eq__ for an unsupported operand so Python can try the other comparison path. This sentinel is not the exception NotImplementedError. Equality is distinct from is; two separate value-equal objects are still distinct instances.
Your code goes in coordinate.py. The locked driver.py is the entry file, supplies execution and checks, and cannot be edited.
Challenge
BeginnerImplement mutable Coordinate(x,y) with __eq__: compare x and y when other is a Coordinate (check with isinstance), otherwise return NotImplemented. The driver creates two coordinates from two integer-pair lines, prints equality and identity, increments the second y, prints equality again, then equality with None. Finally it checks directly that a.__eq__(None) is NotImplemented and prints True.
Implement the named definitions in the editable modules without input or printing. The driver owns input/output and may call the APIs again on fresh data without producing extra output.
C compares meaningful struct fields explicitly; this task practices the Python __eq__ protocol rather than byte comparisons.
Your code goes in coordinate.py. The locked driver.py is the entry file, supplies execution and checks, and cannot be edited.
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 Programs to Python
Run Python Without mainPrinting Without Format CodesNames Versus Typed StorageDivision and Integer LimitsSuites Instead of BracesRecap: A Python Receipt4Iteration and Transformations
Iteration Without PointersIndexes Without Pointer MathSentinels and Loop ControlComprehensions and SortingRecap: Stable Ranking2Values and Truth Tests
Absence Is Not a Null PointerContent Versus Object IdentityTruth Tests and OperandsConditional Value SelectionRecap: Missing or Eligible5Functions and Callbacks
Functions and Object ArgumentsDefaults and Named ArgumentsVarargs Without va_listCallbacks and Captured NamesRecap: Pricing Functions8Composition and Inheritance
Callbacks to CompositionEmbedding Versus InheritanceBehavior Without VtablesEquality and Data ClassesRecap: Pluggable Channels3Containers and Aliasing
Lists Versus C ArraysTuples and Struct ValuesMappings and Lookup LoopsPointers, Copies, and AliasesRecap: Inventory Collections6Contracts, Errors, and Modules
Text Input and Exact OutputError Codes Versus ExceptionsImports Are Not IncludesAnnotations Versus C TypesRecap: Validate a Batch9Project: An Order Processor
Project: Model an OrderProject: Pricing PoliciesPractice on your own: Online Python compiler