Metamethods to Dataclasses
Lesson 41 of 48 in Coddy's Python for Lua Developers course.
Lua tables normally compare by identity, but an equality metamethod can compare selected fields. Python dataclasses generate field-based equality and initialization from annotations. They remain mutable unless configured otherwise, and equality does not imply identity. Ordinary Python classes have identity-based equality until customized. A custom __eq__ should return NotImplemented for unsupported operands, giving the comparison protocol a chance to try other behavior.
Lua example
local mt = {__eq = function(a, b) return a.text == b.text end}
local a = setmetatable({text = "x"}, mt)
local b = setmetatable({text = "x"}, mt)
print(tostring(a == b) .. " " .. tostring(rawequal(a, b)))
b.text = "y"
print(a == b)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)Porting trap
Mutable value-equal Python dataclasses are generally unhashable. Lua table keys instead identify table objects; do not transfer that key model to mutable Python lists or dataclasses.
Implement the specified API in the editable Python files. The locked driver.py runs the program and supplies input/output. Keep its imports and names unchanged.
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 Lua Developers
1From Lua to Python
Run Your First Python ProgramPrinting and TextNames and Local ScopeNumbers and ConversionSuites Instead of endRecap: Rewrite a Receipt4Iteration and Transformations
Numeric for to rangepairs, ipairs, and itemsLoop Control and SkipsComprehensions and SortingRecap: Build a Ranking2Values and Decisions
nil Versus NoneTable Identity and EqualityTruthiness Is Differentelif and Value SelectionRecap: Eligibility Rules5Functions and Closures
Returns and Shared ParametersDefaults and Named CallsVarargs and Call UnpackingUpvalues and Late BindingRecap: Refactor a Pricing Tool8Composition and Dispatch
Composition Shares ObjectsPrototype Chains to superDuck Typing Beyond TablesMetamethods to DataclassesRecap: Notification Channels3Tables to Typed Collections
Sequence Tables to ListsTuples and Multiple ReturnsRecords to DictionariesSets and Shared TablesRecap: Clean an Inventory6Errors and Modules
Input and Exact Textpcall to Exceptionsrequire to importHints and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler