Menu
CoddyTech

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 icon

Challenge

Beginner

Implement 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)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for Java Developers

Practice on your own: Online Python compiler