Menu
CoddyTech

Derived Equality and Dataclass

Lesson 41 of 48 in Coddy's Python for Rust Developers course.

Rust can derive PartialEq to compare struct fields. Python dataclasses can generate initialization, representation, and fieldwise equality from annotated fields. Ordinary Python classes use identity-based equality unless customized. Dataclasses are mutable by default; they are not automatically frozen records. Separate equal dataclass instances are still different objects under is. When implementing Python __eq__ yourself, return the NotImplemented sentinel for unsupported operand types so the comparison protocol can continue.

Rust excerpt inside main

#[derive(PartialEq)]
struct Tag { text: String }
let a = Tag { text: String::from("x") };
let mut b = Tag { text: String::from("x") };
println!("{} {}", a == b, std::ptr::eq(&a, &b));
b.text = String::from("y");
println!("{}", a == b);

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

Mutable value-equal dataclasses are normally unhashable. Do not assume deriving equality makes them safe dictionary keys, and do not confuse NotImplemented with raising NotImplementedError.

Implement the specified API in the editable Python files. The locked driver.py runs the program and supplies input/output. Keep its imports and names unchanged.

challenge icon

Challenge

Beginner

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

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

All lessons in Python for Rust Developers

Practice on your own: Online Python compiler