Note: since this answer keeps getting upvoted - while there are still use cases for TypedDict
, I'd consider using a dataclass
instead today.
I want to have a nice (`mypy --strict` and pythonic) way to turn an untyped `dict` (from `json.loads()`) into a `TypedDict`. My current approach looks like this:
class BackupData(TypedDict, total=False):
archive_name: str
archive_size: int
transfer_size: int
transfer_time: float
error: str
def to_backup_data(data: Mapping[str, Any]) -> BackupData:
result = BackupData()
if 'archive_name' in data:
result['archive_name'] = str(data['archive_name'])
if 'archive_size' in data:
result['archive_size'] = int(data['archive_size'])
if 'transfer_size' in data:
result['transfer_size'] = int(data['transfer_size'])
if 'transfer_time' in data:
result['transfer_time'] = int(data['transfer_time'])
if 'error' in data:
result['error'] = str(data['error'])
return result
i.e I have a TypedDict
with optional keys and want a TypedDict
instance.
The code above is redundant and non-functional (in terms of functional programming) because I have to write names four times, types twice and result
has to be mutable.
Sadly TypedDict
can't have methods otherwise I could write s.th. like
backup_data = BackupData.from(json.loads({...}))
Is there something I'm missing regarding TypeDict
? Can this be written in a nice, non-redundant way?