Records and Data Classes
Lesson 41 of 48 in Coddy's Python for Java Developers course.
Reduce data-holder boilerplate with dataclass. A Java record generates component accessors and value equality and has final component fields. A basic Python dataclass generates an initializer and field-based equality but remains mutable. Its annotations identify fields; they do not validate runtime values. Ordinary classes can implement __eq__ manually, checking the other operand before reading attributes. Return NotImplemented for unsupported types so Python can try the other comparison path. A generated dataclass equality normally requires identical classes, unlike a manual isinstance-based comparison that may accept subclasses.
Java excerpt: class member declarations
// Class member (Java 17)
record Tag(String text) {}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)Watch the difference
NotImplemented is a returned protocol sentinel, not NotImplementedError and not False. Value equality does not imply identity. Neither Java records nor shallow frozen holders recursively freeze referenced collections; this task uses a mutable ordinary class with explicit equality.
Practice
Apply this comparison in the task below. Editable files: coordinate.py. Keep the provided imports and the required API names. The locked driver.py supplies execution and checks; do not edit it.
Challenge
BeginnerImplement mutable Coordinate(x,y) with __eq__: compare x and y when other is a Coordinate (check with isinstance), otherwise return NotImplemented. The driver creates two coordinates from two integer-pair lines, prints equality and identity, increments the second y, prints equality again, then equality with None. Finally it checks directly that a.__eq__(None) is NotImplemented and prints True. A Java record supplies value equality automatically, but this task deliberately practices Python's manual comparison protocol.
Editable files: coordinate.py. Keep the provided imports and the required API names. The locked driver.py supplies execution and checks; do not edit it.
Implement the named definitions in the editable modules without input or printing. The driver owns input/output and may call the APIs again on fresh data without producing extra output.
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 Java Developers
1From Java Classes to Python
Run Python Without a ClassPrinting Text and CommentsBindings, Types, and finalDivision and Numeric TypesIndentation Defines BlocksRecap: A Python Receipt4Iteration and Transformations
Enhanced Loops and rangeIndexes and Map EntriesSentinels and Loop ControlFrom Streams to ComprehensionsRecap: Stable Ranking2Values Beyond Java Primitives
None and Boolean ValuesValue Equality and IdentityTruth Tests Beyond booleanBranches and Value SelectionRecap: Missing or Eligible5Functions Beyond Methods
Functions Outside ClassesDefaults Instead of OverloadsVarargs and Keyword OptionsScope and Callable ObjectsRecap: Pricing Functions8Behavior Beyond Interfaces
Collaborators Without CastsInheritance and InitializationInterfaces and Duck TypingRecords and Data ClassesRecap: Pluggable Channels3Collections and Object Sharing
Lists and ArrayList HabitsTuples Without Record ClassesDictionaries and Java MapsShared References and CopiesRecap: Inventory Collections6Contracts, Errors, and Modules
Text Input and Exact OutputValueError and TypeErrorModules Versus Utility ClassesAnnotations Are Not Java TypesRecap: Validate a Batch9Project: An Order Processor
Project: Model an OrderProject: Pricing PoliciesPractice on your own: Online Python compiler