Menu
CoddyTech

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 icon

Challenge

Beginner

Implement 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)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for C Developers

Practice on your own: Online Python compiler