Regular Dictionary [Ptython Dict] may depend on the TypeDict Class so programmers know what the types of input is.
What is TypedDict?
TypedDict is a way to define the structure of a dictionary with specific key-value type annotations. It’s used for static type checking (e.g., with tools like mypy, pyright, or IDEs) to catch mismatched types during development, but it does NOT enforce types at runtime. Think of it as a "schema" for dictionaries.
Key Features
Static Type Checking:
Helps tools verify that your dictionary keys have the expected types (e.g.,"name"should be astr,"age"should be anint).✅ Catches errors in IDEs or during static analysis.
❌ No runtime validation (you can still assign wrong types).
Use Cases:
Useful when working with structured data (e.g., JSON, configuration dictionaries, API responses) where you want to document/enforce types during development.
Syntax Example
Python 3.8+ (using typing):
from typing import TypedDict class Person(TypedDict): name: str age: int is_student: bool # Optional key (not required unless `total=False` is set)
Python 3.12+ (simpler syntax):
class Person(TypedDict): name: str age: int is_student: bool
How to Use It
# Valid (passes static checks) person: Person = { "name": "Alice", "age": 30, "is_student": False } # Invalid (static type checkers like mypy will flag this) invalid_person: Person = { "name": "Bob", "age": "thirty", # Error: Expected `int`, got `str` }
Runtime Behavior
At runtime, Python ignores TypedDict annotations. This code will not raise errors:
person = Person(name=123, age="thirty") # No runtime error (but mypy will complain)
Runtime Validation Options
If you need runtime type enforcement, use libraries like:
pydantic(validates data at runtime):from pydantic import BaseModel class Person(BaseModel): name: str age: int # Raises ValidationError at runtime for invalid types Person(name="Alice", age="30") # Error: 'age' must be an int
Manual validation (e.g., in
__init__methods).
TypedDict vs. dataclass
TypedDict: For dictionaries with fixed keys/value types (no runtime checks).@dataclass: For class-based objects with enforced types (if you add validation logic).
Summary
TypedDictdefines a type-safe dictionary schema for static analysis tools.It does not enforce types at runtime.
Use
pydanticor similar libraries for runtime validation.
In Python, type annotations (including structures like TypedDict or class __annotations__) do not enforce types at runtime by default. Here's a breakdown:
Type Hints vs. Enforcement:
Type annotations (e.g.,
name: str) are static hints for tools likemypy,pyright, or IDEs. They do not enforce types during execution.Example: You can assign
age: int = "twenty"without runtime errors, even though it violates the type hint.
TypedDict(fromtyping):Defines a dictionary structure with expected key-value types for static analysis.
No runtime validation: A
TypedDictallows invalid types at runtime (e.g.,Person(name=123, age="twenty")won’t raise errors).
Runtime Enforcement Options:
Manual Checks: Add validation in
__init__or setters.Libraries: Use
pydantic,dataclasses(with@dataclassand__post_init__), ortypeguardto enforce types based on annotations.Example with
pydantic:from pydantic import BaseModel class Person(BaseModel): name: str age: int # Raises ValidationError if types mismatch person = Person(name="Alice", age="thirty") # Error: 'age' is not an int
Summary: Type dictionaries (annotations, TypedDict) provide structure for static analysis but do not enforce types at runtime. Use additional tools or manual checks for runtime enforcement.
Comments
Post a Comment