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?
5 Answers
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.
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.
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.
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.
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!
Related Questions
How To: Running Codex CLI on Windows with Azure OpenAI
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically