Struct and Dataclass Equality
Lesson 41 of 48 in Coddy's Python for Ruby Developers course.
An ordinary Ruby object and an ordinary Python object start with identity-oriented equality unless their class customizes it. Ruby Struct provides member-based equality; Python dataclasses can generate initialization, representation, and field equality from annotations. Python dataclasses are mutable by default. The manual __eq__ method in the task makes the protocol visible: compare coordinate fields for a supported type, and return NotImplemented for an unsupported type. NotImplemented is a sentinel, not the NotImplementedError exception. Mutable value-equal dataclasses are normally unhashable, so field equality alone does not make an instance a safe dictionary key.
Ruby
Point = Struct.new(:x, :y)
a = Point.new(1, 2)
b = Point.new(1, 2)
puts(a == b)
puts a.equal?(b)
b.y = 3
puts(a == b)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 use Python is to compare two value records. Dataclass field equality and object identity answer different questions, like Struct equality and equal? in Ruby.
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 Ruby Developers
1From Ruby to Python
Run Your First Python ProgramStrings and InterpolationNames and Mutable StringsDivision and ParsingFrom end to IndentationRecap: Rewrite a Receipt4Iteration and Transformations
each and Python foreach_pair and enumeratenext Becomes continueselect, map, and sort_byRecap: Build a Ranking2Values and Decisions
nil Becomes None== and equal?Zero Is False in Pythonelsif and Conditional ValuesRecap: Eligibility Rules5Functions and Closures
Explicit Return ValuesDefaults Run at DefinitionSplat and Double SplatBlocks Become CallablesRecap: Refactor a Pricing Tool8Composition and Inheritance
Delegating to CollaboratorsExplicit super ArgumentsDuck Typing Without MixinsStruct and Dataclass EqualityRecap: Notification Channels3Collections and References
Array Methods and ListsParallel Assignment and TuplesHash Defaults and Dict Keysdup, Copies, and SetsRecap: Clean an Inventory6Reliable Python Programs
gets, input, and Formattingrescue and Context Managersrequire and Import GuardsHints Do Not Enforce TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler