Value Classes and Dataclasses
Lesson 41 of 48 in Coddy's Python for Dart Developers course.
Dart user classes normally inherit identity-based equality unless operator equality is overridden; a compatible hashCode is then needed for hashed collections. Python ordinary classes also start with identity-oriented equality. A dataclass can generate field equality, initialization, and representation. It is mutable by default and normally unhashable when mutable value equality is generated. In a manual Python __eq__, return NotImplemented for an unsupported operand type rather than raising NotImplementedError. Python is remains the identity operator regardless of value equality. Keep hashing, mutation, and equality consistent when designing records used as keys.
Dart
class Point {
final int x;
final int y;
Point(this.x, this.y);
@override
bool operator ==(Object other) => other is Point && x == other.x && y == other.y;
@override
int get hashCode => x.hashCode ^ y.hashCode;
}
void main() {
final a = Point(1, 2);
final b = Point(1, 2);
print(a == b);
print(identical(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
Adding value equality is not enough to make a mutable record a safe dictionary key. Review hash behavior and mutation together.
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 Dart Developers
1From Dart to Python
Run Your First Python ProgramInterpolation and printvar, final, and Python NamesFloor Versus TruncationBraces and Block ScopeRecap: Rewrite a Receipt4Iteration and Transformations
for-in and rangeentries and enumerateLoop Updates and continuewhere, map, and List BuildingRecap: Build a Ranking2Values and Decisions
Null Safety and NoneList Equality ChangesConditions and Null DefaultsTernaries and elifRecap: Eligibility Rules5Functions and Closures
Arrows and Explicit ReturnsNamed Calls and DefaultsExplicit Variadic ArgumentsClosures and nonlocalRecap: Refactor a Pricing Tool8Composition and Inheritance
Collaborator Objectsextends and Method ResolutionInterfaces and Duck TypingValue Classes and DataclassesRecap: Notification Channels3Collections and References
Lists and Negative IndexesRecords and Tuple UnpackingMap Lookups and KeyErrorSets and Shared ObjectsRecap: Clean an Inventory6Reliable Python Programs
stdin and Exact Formattingon, catch, finally, and withLibraries and Import ExecutionStatic Types Versus HintsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler