Optional Based on an Class/TypedDict Attribute

A class using it would be defined like this

class Somthing(TypedDict):
     error: bool
     data: DynOptional[error, Dict] 

Type checkers could enforce this by throwing a typing error in the IDE, or otherwise if it was not checked

This is most useful when making/consuming an API

from requests import get

data = Somthing(**requests.get(...).json())
data["data"] # Type Error: Data does not exist

assert not data["error"]

data["data"] # no error

This seems like something that can already easily be solved with tagged unions (sort of).

The reason it’s just sort of, is that type checkers are sometimes a bit too eager to reduce unions to a common base type (especially on structural types like TypedDict). That being said, your example already works in mypy with a tagged union: mypy Playground

1 Like