The Problem
TypedDict
s are awesome when you are working with a data model you do not own (i.e., you received some JSON and are required to add/remove one specific field, preferably keeping the order of items). However, sometimes, you want to provide a patch only, or, in other words, partial dict. This would imply that ALL fields are NotRequired
, even those marked with Required
. TypeScript and some other languages have the Partial semantics.
Also, this could be very helpful for the dataclasses, but I assume it is harder to implement.
Example
from typing_extensions import TypedDict
class Structure(TypedDict):
x: int
y: int
def apply_patch(data: Structure, patch: Partial[Structure]) -> Structure:
...
def common_of(*items: Structure) -> Partial[Structure]
....
apply_patch(Structure(x=1, y=2), { 'x': 3 }) # -> { 'x':3, 'y':2 }
common_of(Structure(x=1, y=2), Structure(x=1, y=3)) # -> { 'x': 1 }
Current Solution
Currently, there is no Partial semantics in the language.
There are two workarounds:
- Use
total=False
. This would allow the creation of partial data but will do so in all cases, even if the complete data structure is required. - Use two different classes, one incomplete and one complete (complete derived from partial, or vice versa). This would require a ton of additional classes and sometimes would not be possible.
Similar
- Topic in Help: Is it possible to add a type annotation for partial/not-total typeddicts?
- Question in StackOverflow: type hinting - Python typehint subset(partial) of an TypedDict - Stack Overflow
Updates
Update 1
Code snippet changed: Foo
→ Structure
(artifact of other code snippet)