Chapter 4 · Objects and robust code

Dataclasses, enums and match

You are reading the whole lesson on one page. Back to one step at a time

Step 1 of 21 · Concept

@dataclass writes __init__, __repr__ and __eq__

By the end of this lesson, you can write records, named choices and decisions with less code.

from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int
  • @dataclass is a decorator: it changes the class under it.
  • Each field is a name and its type, x: int. From the fields it writes __init__, __repr__ and __eq__.
from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

p = Point(1, 2)
print(p)
print(p == Point(1, 2))
print([p, Point(0, 0)])
from dataclasses import dataclass

@dataclass
class Item:
    name: str
    price: float
    qty: int = 1

print(Item("pen", 1.5))
print(Item("cup", 2.25, 4))

@dataclass(frozen=True)
class Point:
    x: int
    y: int

origin = Point(0, 0)
try:
    origin.x = 5
except AttributeError:
    print("A frozen Point cannot change")
from dataclasses import dataclass

# write the dataclass Item here

cart = [Item("pen", 1.5), Item("cup", 2.25, 4)]
print(cart[0])
for item in cart:
    print(f"{item.name}: {item.total():.2f}")
from enum import Enum

class Light(Enum):
    RED = 1
    YELLOW = 2
    GREEN = 3

light = Light.YELLOW
print(light)
print(light.name, light.value)
print(light == Light.YELLOW, light == Light.RED)
for light in Light:
    print(light.name)
from enum import Enum

class Light(Enum):
    RED = 1
    YELLOW = 2
    GREEN = 3

def next_light(light):
    return light

light = Light.RED
for i in range(4):
    print(light.name)
    light = next_light(light)
for command in ["go", "halt", "jump"]:
    match command:
        case "go":
            print("Going")
        case "stop" | "halt":
            print("Stopping")
        case _:
            print("Unknown:", command)
from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

def where(p):
    match p:
        case Point(x=0, y=y):
            return f"on the y axis at {y}"
        case _:
            return f"at {p.x}, {p.y}"

pos = Point(0, 0)
for order in ["up 3", "report", "right 2", "report", "jump"]:
    match order.split():
        case ["up", n]:
            pos = Point(pos.x, pos.y + int(n))
        case ["right", n]:
            pos = Point(pos.x + int(n), pos.y)
        case ["report"]:
            print(where(pos))
        case _:
            print("Unknown:", order)
from enum import Enum

class Light(Enum):
    RED = 1
    YELLOW = 2
    GREEN = 3

def next_light(light):
    match light:
        case Light.RED:
            return Light.GREEN
        case _:
            return light

light = Light.RED
for i in range(4):
    print(light.name)
    light = next_light(light)
from dataclasses import dataclass

orders = ["up 3", "right 2", "up 1", "report", "fly 9"]
for order in ["move 12", "move 3", "move 40"]:
    match order.split():
        case ["move", n]:
            print("move", n)
Terminal
Step 1 of 10A Point record

Keyboard shortcuts

The step

ContinueEnter
Previous / next stepAlt+[ · Alt+]
Move along the steps bar← → Home End, then Enter
From a quiz's title to its answers↓
Skip to the stepTab, then Enter (first on the page)
Course outlineAlt+O
These shortcuts?

The workspace

Run the stepCtrl+Enter (⌘↵ on a Mac)
Lesson → editor → consoleF6 (Shift+F6 back)
Output ↔ TerminalCtrl+`
Focus the editorCtrl+. (⌘. on a Mac)
Hide or show the lessonAlt+L
Restore, close a messageEsc (outside the editor and the terminal)

The editor

Leave the editorF6 (Shift+F6 back); or Ctrl+M (⌃⇧M on a Mac), then Tab moves the focus (not in the vim mode)
Open a file by nameCtrl+P (⌘P on a Mac)
All commandsCtrl+Shift+P (⌘⇧P on a Mac) or F1
Go to a lineCtrl+G (⌃G on a Mac)
Show or hide the filesCtrl+B (⌘B on a Mac)
Previous / next file tabCtrl+Shift+[ · Ctrl+Shift+] (⌘⇧[ · ⌘⇧] on a Mac)
The file tabs← → Home End on a tab; Delete closes it
Save the files nowCtrl+S (⌘S on a Mac)
Go to a symbol in the fileCtrl+Shift+O (⌘⇧O on a Mac)
Go to the definitionF12
Format the fileCtrl+Shift+F (⌘⇧F on a Mac), or Shift+Alt+F
Go back / forward after a jumpAlt+← · Alt+→ (⌃- · ⌃⇧- on a Mac)