In typing.TypedDict, there is a difference between fields being NotRequired and fields whose values are declared Optional. The first means that the key may be absent, the latter means the value on an existing key may be None.
In my context (working with mongodb), I do not want to differentiate this, and simply allow a field to be both NotRequired and Optional. This could be achieved by
class Struct(TypedDict):
possibly_string = NotRequired[str | None]
In my context I never want to differentiate this, so I would like to have a generic type, say Possibly[T] which I can use as a shorthand for writing NotRequired[T | None].
When I try to write a generic alias, mypy gives me the two errors indicated in the code comments:
from typing import NotRequired, Optional, TypeVar, TypedDict
T = TypeVar("T")
Possibly = NotRequired[Optional[T]]
class Struct(TypedDict):
possibly_string: Possibly[str] # Variable "Possibly" is not valid as a type [valid-type]
non_compliant: Struct = {"possibly_string": int}
compliant_absent: Struct = {} # Missing key "possibly_string" for TypedDict "Struct" [typeddict-item]
compliant_none: Struct = {"possibly_string": None}
compliant_present: Struct = {"possibly_string": "a string, indeed"}
Is it possible to achieve what I want? If so, how?
I look for a solution for Python3.11 or upwards.