Equality and Data Classes
Lesson 41 of 48 in Coddy's Python for JavaScript Developers course.
Decide whether two objects represent the same value, and use a data class when storing and comparing fields is the main job. Identity still asks a separate question: whether two references point to one object.
JavaScript
class Point {
constructor(x) { this.x = x; }
}
const a = new Point(2), b = new Point(2);
console.log(a === b ? "same" : "different");
console.log(a.x === b.x ? "equal" : "unequal");Python
from dataclasses import dataclass
@dataclass
class Point:
x: int
a, b = Point(2), Point(2)
print("same" if a is b else "different")
print("equal" if a == b else "unequal")What changes
Both programs print different then equal, but the equality checks do different work. JavaScript compares the fields explicitly here. Python's @dataclass generates initialization and equality from annotated fields; ordinary generated equality compares field values for instances of the same class. The annotations describe fields, not runtime type validation. For a regular class you can define __eq__(self, other) yourself. Use isinstance(other, YourClass) to check supported operands, compare their fields, and return NotImplemented for unsupported operands. That special result lets Python try the other operand's comparison behavior.
For a complete small manual comparison, the following class supports only other Code instances:
class Code:
def __init__(self, text):
self.text = text
def __eq__(self, other):
if not isinstance(other, Code):
return NotImplemented
return self.text == other.text
print(Code("x") == Code("x"))Common mistake
Do not replace value equality with is. Separate equal data objects remain distinct instances. Returning False for an unsupported operand also differs from returning NotImplemented: it settles your comparison instead of giving the other operand a chance. List membership uses equality, which makes a list useful for ordered deduplication without introducing sets of objects.
Your task
Write explicit coordinate equality first. The optional mastery uses generated data-class equality to keep the first occurrence of each reading.
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 JavaScript Developers
1From JavaScript to Python
Run Your First Python ProgramPrint, Comments, and StringsVariables Without let or constNumbers and ConversionBlocks Use IndentationRecap: Rewrite a Receipt4Iteration and Transformations
for Loops Iterate ValuesIndexes and Dict Iterationwhile, break, and continueComprehensions and SortingRecap: Build a Ranking2Values and Decisions
None, True, and FalseEquality and IdentityTruthiness and Short-CircuitBranches and ExpressionsRecap: Eligibility Rules5Functions and Scope
Define and ReturnPositional and Keyword ArgsExtra Arguments and UnpackingScope, Callbacks, and LambdasRecap: Refactor a Pricing Tool8Composition and Inheritance
Composition FirstInheritance and superPolymorphism and Duck TypingEquality and Data ClassesRecap: Notification Channels3Collections and References
Lists Instead of ArraysTuples and UnpackingDictionaries and RecordsSets, Aliasing, and CopiesRecap: Clean an Inventory6Reliable Python Programs
Input and Output ContractsExceptions and ValidationModules and the Main GuardReading Type HintsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler