-
-
Notifications
You must be signed in to change notification settings - Fork 3k
Description
Is there a way to use TypedDict for more complicated nested structures? For example, if I pass around a dictionary with certain defined keys and values, some of which are dictionaries themselves, can I validate those?
-
Are you reporting a bug, or opening a feature request?
Asking a question/maybe feature request -
Please insert below the code you are checking with mypy,
or a mock-up repro if the source is private. We would appreciate
if you try to simplify your case to a minimal repro.
from mypy_extensions import TypedDict
Data = TypedDict("Data", {"i": {"j": int}})
def access(data: Data) -> None:
data["i"]["j"] += 1
mydata = {"i": {"j": 5}} # type: Data
access(mydata)
- What is the actual behavior/output?
typeddict_practice.py:3: error: Invalid field type
typeddict_practice.py:7: error: TypedDict "TypedDict" has no key 'i'
typeddict_practice.py:10: error: Extra key 'i' for TypedDict "TypedDict"
-
What is the behavior/output you expect?
No output -
What are the versions of mypy and Python you are using?
mypy 0.600
Python 3.6.5 -
What are the mypy flags you are using? (For example --strict-optional)
None
I can use something like Data = TypedDict("Data", {"i": Dict[str, int]})
, but that doesn't validate keys past the first level.
I can also do
Intermediate = TypedDict("Intermediate", {"j": int})
Data = TypedDict("Data", {"i": Intermediate})
but this is cumbersome, especially when there are a ton of fields. As #4299 notes, you can't nest TypedDicts either. Is there a better way?