Dataclasses, enumerations and types · 11 / 15 Exercise Medium

Immutable dataclass

Objective

Create a Python program with an immutable dataclass (frozen=True) and create modified versions with replace.

Instructions

  • Import dataclass, replace and FrozenInstanceError from dataclasses. Define @dataclass(frozen=True) class Coordinate with lat: int and lon: int.
  • Read a line with two integers, lat lon, and create the coordinate.
  • Show Original: followed by the object. Try to do c.lat = 0 inside a try; if FrozenInstanceError is raised, show Cannot be modified.
  • Create a new coordinate with replace(c, lat=c.lat + 1) and show New: followed by the object.
Input
10 20
Output
Original: Coordinate(lat=10, lon=20)
Cannot be modified
New: Coordinate(lat=11, lon=20)

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise