xSKILLby Infirals
Register

Python for Beginners

0 of 24 notes read 0%

Reading progress is saved to your INFIRALS account. Sign in to keep this note marked as read.

Type hints and dataclasses

More Python10 min readLesson 6 of 7

6.1 Hints are documentation for people and tools

Python does not enforce type hints at runtime, but editors and tools like mypy use them to catch mistakes before a program runs. Start with function signatures and data shapes; precise annotation of every local variable is rarely worth it.

A dataclass generates __init__, __repr__ and equality from annotated fields. It is the shortest sensible way to define a small record such as a lesson or a timetable block.

python
from dataclasses import dataclass

@dataclass
class Lesson:
    title: str
    minutes: int = 8

lesson = Lesson("Loops", 12)
print(lesson)
print(lesson.minutes)

Output

Lesson(title='Loops', minutes=12)
12

Use list[str] and dict[str, int] for containers. Optional values are str | None (Python 3.10 and newer). A dataclass with frozen=True becomes immutable, which is useful for values that should not be changed after creation.

Interview questions

2 questions from this note. Open one to see the answer; no account needed.

  • 01Do type hints affect how the program runs?

    Not normally. They are checked by external tools and editors; the interpreter ignores them.

  • 02Why use a dataclass instead of a plain class?

    It writes the repeated constructor and comparison methods for you, so the definition stays focused on fields.