Fullstack Python
Trang chủ / Module 1
🐍 Module 1 / 19 · 4 ngày 📅 Tuần 1 ●●○○ Trung bình

Python hiện đại: type hints, dataclass, pattern matching, generator, decorator

Viết Python như kỹ sư production năm 2026: type hints đầy đủ, dataclass và enum, structural pattern matching, comprehension và generator, context manager, decorator, exception có cấu trúc và ExceptionGroup.

Type hintsDataclassPattern matchingGeneratorContext managerDecorator
📌 Vì sao module này quan trọng

Python dễ viết nên cũng dễ viết tệ: hàm nhận dict không rõ cấu trúc, trả về None hoặc tuple tuỳ trường hợp, không kiểu, không test. Ở mức lương $5000, codebase Python được kỳ vọng an toàn kiểu (type hints + mypy/pyright), dễ đọc và dùng đúng các thành ngữ của ngôn ngữ. Đây cũng là nhóm câu hỏi mở đầu của mọi vòng phỏng vấn Python: mutable default argument, generator, decorator, closure.

🎯 Mục tiêu học tập

  • Khai báo kiểu đầy đủ: built-in generics, Optional/union, TypedDict, Literal, Protocol, TypeVar và cú pháp generic mới
  • Dùng dataclass, enum và value object bất biến thay dict tự do
  • Dùng pattern matching, comprehension, generator và itertools đúng chỗ
  • Viết context manager và decorator có kiểu
  • Xử lý lỗi bằng exception có cấu trúc; tránh các bẫy kinh điển của Python

Type hints là bắt buộc

from collections.abc import Iterable, Sequence
from typing import Literal, TypedDict, Protocol

Status = Literal["todo", "doing", "done"]

class TaskDict(TypedDict):           # mô tả dict từ JSON/API khi chưa chuyển thành model
    id: int
    title: str
    status: Status

def total_minutes(tasks: Iterable["Task"]) -> int:
    return sum(t.estimate_minutes or 0 for t in tasks)

def find_task(tasks: Sequence["Task"], task_id: int) -> "Task | None":
    return next((t for t in tasks if t.id == task_id), None)

class Notifier(Protocol):            # duck typing có kiểu: không cần kế thừa
    def send(self, to: str, message: str) -> None: ...

# Python 3.12+: cú pháp generic mới
def first[T](items: Sequence[T]) -> T | None:
    return items[0] if items else None

type UserId = int                    # type alias (3.12+)
  • Type hints không được kiểm tra lúc chạy — cần mypy hoặc pyright trong CI (Module 2), và Pydantic để validate dữ liệu thật tại biên (Module 4).
  • Python 3.14 đánh giá annotation trì hoãn (PEP 649) — ít cần chuỗi forward reference hơn.

Dataclass, enum và value object

from dataclasses import dataclass, field
from enum import StrEnum
from decimal import Decimal

class OrderStatus(StrEnum):
    PENDING = "pending"
    PAID = "paid"
    CANCELLED = "cancelled"

@dataclass(frozen=True, slots=True)          # bất biến, tiết kiệm bộ nhớ
class Money:
    amount: Decimal                          # tiền: Decimal hoặc int đơn vị nhỏ nhất — không float
    currency: str = "VND"

    def __post_init__(self) -> None:
        if self.amount < 0:
            raise ValueError("Số tiền âm")

    def __add__(self, other: "Money") -> "Money":
        if other.currency != self.currency:
            raise ValueError("Khác loại tiền")
        return Money(self.amount + other.amount, self.currency)

@dataclass(slots=True)
class Cart:
    items: list["CartItem"] = field(default_factory=list)   # KHÔNG dùng items: list = []

0.1 + 0.2 != 0.3 với float — lý do không dùng float cho tiền. Dataclass cho object nội bộ; Pydantic cho dữ liệu cần validate từ bên ngoài.

Pattern matching, comprehension, generator

def handle(event: dict) -> str:
    match event:
        case {"type": "payment.succeeded", "data": {"amount": int(amount)}} if amount > 0:
            return f"Đã thanh toán {amount}"
        case {"type": "payment.failed", "data": {"reason": reason}}:
            return f"Thất bại: {reason}"
        case {"type": str(t)}:
            return f"Bỏ qua sự kiện {t}"
        case _:
            raise ValueError("Sự kiện không hợp lệ")

# Comprehension — rõ ràng hơn map/filter cho trường hợp đơn giản
open_titles = [t.title for t in tasks if t.status != "done"]
by_id = {t.id: t for t in tasks}

# Generator — xử lý dữ liệu lớn với bộ nhớ hằng số
def read_rows(path: str):
    with open(path, encoding="utf-8") as f:
        for line in f:
            yield line.rstrip("\n").split(",")

total = sum(int(row[2]) for row in read_rows("orders.csv"))   # không load cả file vào RAM

itertools (batched, groupby, chain, islice) và functools (cache, partial, reduce) giải phần lớn bài xử lý dữ liệu mà không cần thư viện ngoài.

Context manager và decorator

from contextlib import contextmanager
from functools import wraps
import time, logging
from collections.abc import Callable

@contextmanager
def timed(name: str):
    start = time.perf_counter()
    try:
        yield
    finally:                                  # chạy cả khi có lỗi
        logging.info("%s took %.1fms", name, (time.perf_counter() - start) * 1000)

def retry[**P, R](times: int = 3) -> Callable[[Callable[P, R]], Callable[P, R]]:
    def decorator(fn: Callable[P, R]) -> Callable[P, R]:
        @wraps(fn)                            # giữ tên, docstring của hàm gốc
        def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
            for attempt in range(times):
                try:
                    return fn(*args, **kwargs)
                except ConnectionError:
                    if attempt == times - 1:
                        raise
                    time.sleep(2 ** attempt)
            raise AssertionError("unreachable")
        return wrapper
    return decorator

with timed("export"):
    export_report()

Exception và các bẫy kinh điển

BẫyVí dụSửa
Mutable default argumentdef add(item, items=[]) — list dùng chung giữa mọi lần gọiitems: list | None = None rồi tạo mới trong hàm
Late binding closure[lambda: i for i in range(3)] đều trả 2lambda i=i: i
Bắt lỗi quá rộngexcept Exception: pass nuốt mọi bugBắt lỗi cụ thể, log, re-raise
is vs ==x is 1000is chỉ cho None, singleton
Sửa list khi đang lặpfor x in items: items.remove(x)Tạo list mới bằng comprehension
class DomainError(Exception): ...
class InsufficientStock(DomainError):
    def __init__(self, sku: str, available: int, requested: int) -> None:
        super().__init__(f"{sku}: còn {available}, yêu cầu {requested}")
        self.sku, self.available, self.requested = sku, available, requested

try:
    reserve(sku, 5)
except InsufficientStock as e:
    raise OrderRejected("Không đủ hàng") from e       # giữ chuỗi nguyên nhân

# ExceptionGroup (3.11+) — nhiều lỗi từ các tác vụ song song
try:
    async with asyncio.TaskGroup() as tg: ...
except* TimeoutError as eg:
    ...

🏋️ Bài tập thực hành

Viết lại một script Python 'kiểu cũ' thành module production

Lấy (hoặc tự viết) một script xử lý đơn hàng dùng dict tự do, float cho tiền, except: pass. Viết lại: (1) type hints đầy đủ, chạy pyright/mypy strict không lỗi; (2) StrEnum cho trạng thái có quy tắc chuyển; (3) dataclass frozen Money, Address; (4) đọc file CSV 1 triệu dòng bằng generator, đo bộ nhớ trước/sau; (5) decorator retry và context manager timed có kiểu; (6) exception nghiệp vụ riêng. Viết test pytest cho mọi quy tắc.

📚 Tài nguyên học tập

✅ Tự đánh giá hoàn thành

  • Code có type hints đầy đủ và qua kiểm tra kiểu strict
  • Dùng dataclass/enum thay dict tự do; tiền không dùng float
  • Dùng generator cho dữ liệu lớn; viết được decorator và context manager
  • Tránh được các bẫy kinh điển và giải thích được vì sao