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

0
14
Asked By CuriousCoder42 On

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

Answered By TechSavvy77 On

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.

Answered By CodeMaster2023 On

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.

Answered By SyntaxWhiz On

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.

Answered By DevDude101 On

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.

Answered By DataNinja99 On

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

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.