Why Isn't TypedDict Enforcing Key Types and Values as Expected?

April 24, 2025 5 answers
Asked by +second opinion
I'm dealing with a `TypedDict` in Python, and I'm a bit confused. I thought `TypedDict` was meant to restrict both the types and the keys of dictionaries. However, my code is running without any errors even when I include extra keys and use different data types than expected. Here's a simplified version of what I'm working with: ```python from typing import TypedDict class State(TypedDict): """ A class representing the state of a node. Attributes: graph_state(str) """ graph_state: str p1:State={"graph_state":1234,"hello":"world"} print(f"{p1["graph_state"]}") State=TypedDict("State",{"graph_state":str}) p2:State={"graph_state":1234,"hello":"world"} print(f"{p2["graph_state"]}") ``` Can anyone explain why this isn't throwing any type errors? Is the purpose of `TypedDict` not to enforce the structure of the dictionary like I thought?

Answers

probability novice
Itโ€™s important to remember that TypedDict is mainly a hint for type checkers. If you want stricter runtime checks, tools like Pydantic might be the way to go. Otherwise, your code will run as it is, just without those enforced types!
Reply to this answer
!round of applause
For runtime enforcement, consider implementing your own checks or using libraries like Pydantic. Itโ€™s a good idea for ensuring data validation if thatโ€™s a critical part of your application.
Reply to this answer
conic_sections
Right! The typing hints are primarily for tools to help catch issues before runtime. If you donโ€™t run those checks, Python wonโ€™t complain about the types or extra keys.
Reply to this answer
blitz-5min
Exactly! Unless you're using a tool that actively checks types during execution, like mypy, the typing system will just serve as guidelines. So go ahead and use Pydantic if you need stricter enforcement.
Reply to this answer
shoelace.aglet
TypedDicts are essentially just regular dictionaries at runtime. The restriction you're expecting applies only when using type checking tools like mypy, not during execution. So, although it seems like you can have any keys and types, that's just how Python's typing system operatesโ€”it provides guidance but doesn't enforce it unless a type checker is used.
Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions