pyodide: loading…

[concept]OOP & Tooling

Type Hints & Dataclasses

# theory

Type hints document what goes in and what comes out. Python does not enforce them at runtime, but they make code readable and let editors catch mistakes.

def add(a: int, b: int) -> int:
    return a + b

@dataclass writes the boilerplate for you. You declare the fields with types and it generates __init__, __repr__, and __eq__.

from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

Point(1, 2) now prints as Point(x=1, y=2) and two points with the same values compare equal. No hand-written __init__ needed.

# examples [2]

# example 01 · typed function

Hints describe the inputs and the return value

1
2
3
4
5
🐍
Loading PythonSetting up pandas & numpy...
# example 02 · dataclass gives you __repr__ and __eq__ free

Declare fields with types; the boilerplate is generated

1
2
3
4
5
6
7
8
9
10
11
12
13
🐍
Loading PythonSetting up pandas & numpy...

# challenges [2]

# challenge 01/02todo
Write a function add(a: int, b: int) -> int that returns the sum, then print the result of add(2, 3) in the form sum=<value>.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
🐍
Loading PythonSetting up pandas & numpy...
# challenge 02/02todo
Use @dataclass to define a class Point with fields x: int and y: int. Create Point(1, 2) and print it. The dataclass repr should show Point(x=1, y=2).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
🐍
Loading PythonSetting up pandas & numpy...