Records and Generated Equality
Lesson 41 of 48 in Coddy's Python for R Developers course.
R identical compares structure, values, and types for ordinary objects; Python ordinary user classes default to identity-oriented equality unless customized. A Python dataclass can generate field-based initialization, representation, and equality from annotations. It remains mutable unless configured otherwise. For a manual __eq__, compare supported fields and return NotImplemented for unsupported operand types so Python can continue its protocol. That sentinel differs from raising NotImplementedError. A mutable value-equal dataclass is normally unhashable. R list-copy behavior also differs from Python mutable instance sharing, so separate the equality rule from the mutation model.
R
a <- list(x=1L, y=2L)
b <- list(x=1L, y=2L)
cat(identical(a, b), "\n", sep="")
b$y <- 3L
cat(identical(a, b), "\n", sep="")Python
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
a = Point(1, 2)
b = Point(1, 2)
print(a == b)
print(a is b)
b.y = 3
print(a == b)Porting trap
Do not translate R identical to Python is for value records. Python is checks identity, while dataclass equality checks fields.
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 R Developers
1From R to Python
Run Your First Python Programcat, print, and StringsBindings and Copy SemanticsInteger Arithmetic and NABraces Become SuitesRecap: Rewrite a Receipt4Iteration and Transformations
seq_along and rangeitems and enumeratenext and continuelapply and ComprehensionsRecap: Build a Ranking2Values and Decisions
NULL, NA, and NoneVector Equality and IdentityScalar Conditions, Not Vectorsifelse and Scalar SelectionRecap: Eligibility Rules5Functions and Environments
Explicit Function ReturnsLazy and Eager DefaultsDots Versus Star ArgumentsEnvironments and nonlocalRecap: Refactor a Pricing Tool8Composition and Dispatch
Store a CollaboratorNextMethod and superGenerics to Duck TypingRecords and Generated EqualityRecap: Notification Channels3Vectors to Containers
Vectors, Lists, and Index ZeroTuples and Exact UnpackingNamed Lists and Dictionariesunique and Shallow CopiesRecap: Clean an Inventory6Reliable Python Programs
readLines and Text ContractsConditions and Cleanupsource and Module ImportsAnnotations and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler