smartyfy.mrindigi.com

Python Master Course V2 — 106. Advanced Type Hints and Protocols

SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · MODULE 11 · LESSON 106 OF 200

Advanced Type Hints and Protocols

Study: 90–120 minutes · Prerequisites: Lessons 101–102, functions, classes, exceptions and tests.

Course hub

Video lesson

Video not yet available. A verified video URL/player will be added when supplied.

Learning outcomes

Explain advanced type hints and protocols, reason about runtime behavior, apply the technique in a maintainable program, and test normal, boundary and invalid inputs.

Understand and apply: Advanced Type Hints and Protocols

Type hints describe expected interfaces for static checkers but do not enforce values at runtime. Protocol supports structural typing, while generics express relationships between types.

Describe an interface without prescribing inheritance

A type annotation communicates a contract to readers and static analysis tools. A protocol describes the attributes or methods a consumer requires. Structural typing means a class can satisfy that protocol by providing compatible members, without inheriting from it. This is useful for repositories, clocks and transports: production and test implementations can share a small interface while storing or obtaining data differently.

Choose annotations that express what the caller actually needs. An Iterable allows iteration but does not promise indexing, a length or repeated traversal. A Product | None result makes absence explicit, so callers must handle the missing case before using Product attributes. Generic type variables preserve a relationship between input and output types instead of discarding that information with Any.

Python file: lesson106.py

from dataclasses import dataclass
from typing import Iterable, Protocol, TypeVar

@dataclass(frozen=True)
class Product:
    sku: str
    qty: int

class Repository(Protocol):
    def get(self, sku: str) -> Product | None: ...

class MemoryRepository:
    def __init__(self, products: Iterable[Product]) -> None:
        self._products = {product.sku: product for product in products}

    def get(self, sku: str) -> Product | None:
        return self._products.get(sku)

def stock(repo: Repository, sku: str) -> int:
    product = repo.get(sku)
    if product is None:
        raise LookupError("unknown sku")
    return product.qty

T = TypeVar("T")

def first(items: Iterable[T]) -> T | None:
    return next(iter(items), None)

if __name__ == "__main__":
    repo: Repository = MemoryRepository([Product("PEN", 7)])
    print(stock(repo, "PEN"))
    print(repo.get("MISSING"))
    print(first(["Asha", "Mei"]))

Expected output

7
None
Asha

MemoryRepository meets the get contract through its method signature. stock checks None before returning qty; after that check a static analyzer can narrow product to Product. Calling first on strings produces a str-or-None result, while calling it on integers produces int-or-None. The implementation consumes one item from an iterator, which is an observable behavior the annotation alone does not explain.

Make the static check an actual project step

Use a Python 3.10–3.13 virtual environment for this reproducible checker exercise. The pinned version below is an exercise dependency, not a claim that it is the latest release. These are terminal commands; do not paste them into a Python file. On Windows, use .venv\Scripts\python.exe in place of .venv/bin/python.

Shell commands (macOS/Linux)

python3 -m venv .venv
.venv/bin/python -m pip install mypy==1.15.0
.venv/bin/python -m mypy --strict lesson106.py

Expected output

Success: no issues found in 1 source file

Python file: bad_repository.py (intentional static type error)

from lesson106 import Repository

class BrokenRepository:
    def get(self, sku: str) -> str:
        return "seven"

broken: Repository = BrokenRepository()

Shell command: check the intentionally incompatible implementation

.venv/bin/python -m mypy --strict bad_repository.py

Expected diagnostic: the assignment is incompatible because BrokenRepository.get returns str where the protocol requires Product | None. The checker should exit unsuccessfully; exact line numbers and explanatory formatting can vary. This failure demonstrates the interface check. Running Python alone will still perform the assignment, because annotations do not insert runtime validators.

Validate untrusted CSV, JSON and user input before constructing Product objects. A frozen dataclass prevents ordinary attribute reassignment, but it does not validate qty or make arbitrary nested objects deeply immutable. Similarly, runtime_checkable protocols support limited runtime member checks rather than verifying complete signatures or return types. Avoid using cast or Any to silence an error that actually indicates an incompatible repository.

Project completion means a compatible implementation passes strict checking, an intentionally incompatible one fails for the expected reason, a missing product follows the documented LookupError path, and ordinary runtime tests still verify the returned quantities. Static checking and tests answer different questions, so retain both.

Progressive runnable examples

Requires Python 3.10+. Save as lesson106.py and run python lesson106.py or python3 lesson106.py. Expected outputs below are illustrative and not claimed to have been executed on Smartyfy.

Example 1 — Core mechanism

from typing import Protocol
class Named(Protocol):
    name: str
class Person:
    def __init__(self, name: str) -> None:
        self.name = name
def label(item: Named) -> str:
    return item.name.upper()
print(label(Person('Asha')))

Expected output:

ASHA

Guided practical project

Project: Define a typed repository protocol and run a static checker on two implementations.

Use the complete implementation and explicit contract in the worked explanation above. Reproduce its deterministic sample, test the stated boundary and failure cases, and explain the documented limitations before adapting it.

Common mistakes and debugging

  • Adding abstraction without a demonstrated need.
  • Hiding state or unexpected side effects.
  • Assuming type hints replace validation.
  • Ignoring resource cleanup or error propagation.
  • Measuring performance on unrepresentative data.
  • Failing to test boundary and error cases.

Debug by reproducing the smallest failing input, inspecting the traceback and intermediate values, then adding a regression test.

Practice with explained answers

Predict each result before opening the answer. Explain how the design handles both ordinary and boundary cases.

Must MemoryRepository inherit from Repository?

No. Structural compatibility comes from its get method accepting the required argument and returning Product | None. Explicit inheritance is optional; the typed repo assignment asks the checker to verify compatibility.

Why check product is None before reading product.qty?

get explicitly permits absence. The check gives the missing case a defined exception and narrows the remaining branch to Product for the checker. Reading qty immediately would be unsafe for a missing SKU.

What relationship does TypeVar preserve in first()?

Its T links the iterable element type to the possible return type. Iterable[str] gives str | None, and Iterable[int] gives int | None. Returning Any would lose that information and allow many erroneous operations to pass unchecked.

Why does BrokenRepository fail despite having a method named get?

Member names alone are insufficient for static protocol compatibility. Its return value is annotated str, incompatible with the required Product | None. The consumer expects product.qty, which strings do not provide.

Will Product("PEN", "seven") automatically fail at runtime?

No. Dataclass annotations do not validate constructor values. A checker should flag that literal call, but data loaded at runtime still needs explicit validation. Frozen controls reassignment, not accepted input types.

Does runtime_checkable prove an implementation has correct method types?

No. Its runtime checks are limited to the required members, rather than a full verification of argument and return annotations. Use a static checker for interface compatibility and runtime tests for behavior and validation.

Mastery checkpoint

Explain the concept without notes, reproduce the core example, finish the project, run three tests and justify when the technique is appropriate. No account-synced completion or certification is claimed.

Course hub · Previous lesson 105 is available through the hub · Next lesson 107 will be linked after publication.

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.