N
NexusDigitalLabs
← Back to Academy

Phase 1 — Foundations · Lesson 3 · 20 XP

Python core II: functions, dataclasses, pathlib, file I/O

@dataclass turns a class into a labeled bundle of fields — Python generates __init__, a readable __repr__, and equality for you, so you stop hand-writing boilerplate constructors.

@dataclass
class Book:
    title: str
    author: str
    year: int
    pages: int = 0   # optional, has a default

b = Book("Dune", "Frank Herbert", 1965)
print(b)   # Book(title='Dune', author='Frank Herbert', year=1965, pages=0)

pathlib.Path replaces string paths and os.path. `/` joins paths across platforms; the rest reads naturally:

p = Path("data") / "report.txt"
p.exists()
p.read_text()
p.write_text("hello")
p.glob("*.txt")   # iterator of matching files in that folder

text.splitlines() splits a string into lines without trailing newlines. "\n".join(list_of_strings) is the reverse. str.strip() cleans up whitespace on lines you read back in.

Exercise

Model a Book with @dataclass, write a describe() formatter, write a report of several books to a file with write_text, read it back with read_text + splitlines, and count words across every .txt file in a folder with glob.

Check yourself

1. What three things does @dataclass generate for you automatically?

2. Why should read_lines check path.exists() before reading — what happens without that check?

← Previous lesson

Python core I: types, data structures, comprehensions

Answer the check-yourself questions to unlock this