0Pricing
Python Academy · Lesson

TypeVar, Generic Classes, and Protocol

Define reusable generic types and structural subtyping with Protocol.

What Is TypeVar?

TypeVar declares a type variable — a placeholder that can be any type, constrained if needed. Used in generic functions and classes.

from typing import TypeVar

T = TypeVar("T")

def identity(value: T) -> T:
    return value

print(identity(42))      # int
print(identity("hello")) # str

Generic Functions

A function using TypeVar in both parameter and return types allows mypy to infer the return type from the argument type.

from typing import TypeVar

T = TypeVar("T")

def first(items: list[T]) -> T:
    return items[0]

x: int = first([1, 2, 3])     # mypy knows x is int
s: str = first(["a","b","c"]) # mypy knows s is str

All lessons in this course

  1. Basic Type Annotations
  2. Complex Types: List, Dict, Optional, Union
  3. TypeVar, Generic Classes, and Protocol
  4. Running mypy and Fixing Type Errors
← Back to Python Academy