Python 3D Academyবাংলা

Precise hints: generics, Protocol, TypedDict and Literal

🌍 In real life. Labels can be more precise than "box":

  • a lunch box that says "what goes in comes out": put rice in, get rice back; put fruit in, get fruit back
  • a socket that says "anything with this plug": it doesn't care which company made the kettle
  • an admission form with exactly these blanks: name (text), age (number)
  • a bus ticket that is "AC" or "non-AC", and nothing else

Python's type hints (Lessons 29.1–29.3) have a tool for each of these.

The idea in one sentence: a type variable lets a hint say "the same type comes out as went in", a Protocol says "anything with these methods", a TypedDict says "a dict with exactly these keys", and Literal says "only these exact values".

Its words:

  • type variable: a stand-in name, T, for "some type, the same each time it appears"; def first[T](items: list[T]) -> T (Python 3.12 and later)
  • generic: a function or class written with a type variable, so it works for many types and keeps track of which
  • Protocol: a class that lists methods; any class with those methods fits, without inheriting from it (duck typing, Lesson 22.3, written as a hint)
  • TypedDict: names each key of a dict and the type of its value
  • Literal["S", "M", "L"]: only these values are allowed

Step by step, for first([30, 10, 20]):

  1. The list is a list[int], so for this call T stands for int.
  2. The hint -> T then says the answer is an int: a checker knows top + 1 is fine.
  3. For first(["tea", "coffee"]), T is str, and the answer is a str.
  4. When the program runs, nothing extra happens: hints are labels for people and checkers.

Protocol: a hint for duck typing. In Lesson 22.3 a Duck and a Robot both had speak(), and one loop worked for both. A Protocol writes that rule down: "a Speaker is anything with a speak() that returns a str". Neither class has to inherit from Speaker; a checker looks at the methods they have.

from typing import Protocol


class Speaker(Protocol):
    def speak(self) -> str: ...


class Duck:
    def speak(self) -> str:
        return "Quack"


class Robot:
    def speak(self) -> str:
        return "Beep"


def greet_all(things: list[Speaker]) -> None:
    for thing in things:
        print(thing.speak())


greet_all([Duck(), Robot()])
The ... is the method's whole body: a Protocol only describes, it does nothing itself.
from typing import Literal, TypedDict


class Contact(TypedDict):
    name: str
    phone: str


Seat = Literal["AC", "non-AC"]


def ticket(who: Contact, seat: Seat) -> str:
    return f"{who['name']}: {seat}"


c: Contact = {"name": "Mina", "phone": "017-111"}
print(ticket(c, "AC"))
print(type(c).__name__)
At run time a TypedDict value is a plain dict. The checking happens in your editor or in a checker like mypy.

The older spelling. Before Python 3.12, type variables were made by hand: T = TypeVar("T"), then def first(items: list[T]) -> T:. You will see this in a lot of code; it means the same.

What it costs. Nothing at run time. In return, a checker can catch a wrong key in a dict, a size that doesn't exist, or an object missing a method, before anyone runs the program.

Mistakes and edge cases.

  • Expecting Python to enforce them. ticket(c, "first class") runs without complaint; only a checker flags it. Guard real input yourself (Lesson 29.4).
  • isinstance with a TypedDict. isinstance(c, Contact) gives TypeError: TypedDict does not support instance and class checks. At run time it is just a dict: check its keys instead.
  • isinstance with a Protocol. isinstance(Duck(), Speaker) gives TypeError: Instance and class checks can only be used with @runtime_checkable protocols. Add @runtime_checkable from typing if you really need it.
  • A type variable used once. def show[T](x: T) -> None adds nothing over x: object. A type variable earns its place when it links two things, like what goes in and what comes out.

Quiz

  1. def first[T](items: list[T]) -> T. What does a checker know about first(["a", "b"])?

    • It is a str
    • It is a list
    • Nothing: T could be any type
  2. What does this print?

    from typing import TypedDict
    
    
    class Point(TypedDict):
        x: int
        y: int
    
    
    p: Point = {"x": 1, "y": 2}
    print(type(p).__name__, p["x"] + p["y"])
  3. Speaker is a Protocol with speak(). Robot has a speak() but doesn't inherit from Speaker. Does a checker accept a Robot where a Speaker is wanted?

    • Yes: a Protocol only asks for the methods
    • No: Robot must inherit from Speaker
    • Only if Robot also has __init__
  4. A checker flags this before it runs, and Python stops with KeyError: 'XL'. Which line breaks the hint?

    from typing import Literal
    
    Size = Literal["S", "M", "L"]
    
    
    def price(size: Size) -> int:
        return {"S": 20, "M": 30, "L": 40}[size]
    
    
    print(price("XL"))
  5. What does this print?

    from typing import Literal
    
    
    def move(direction: Literal["up", "down"]) -> str:
        return "going " + direction
    
    
    print(move("sideways"))

Coding tasks

  1. Write a generic function with the new syntax, def last[T](items: list[T]) -> T | None:, that returns the last item, or None for an empty list.

  2. Make Book, a TypedDict with title: str and pages: int. Then write reading_time(book: Book, speed: Literal["slow", "fast"]) -> int: 2 minutes a page when slow, 1 when fast.