Using TypedDict with invalid attribute names
Posted 17 April 2024
I've previously covered how to use generic types for TypedDict values but another challenge you can run into when using TypedDict
is in cases where a key name is not a valid identifier. In Python, identifiers (or names) are limited on the characters they can contain (generally uppercase and lowercase letters A
through Z
, the underscore _
and digits 0
through 9
).
You'll generally use TypedDict
by defining a class:
from typing import TypedDict
class Book(TypedDict):
id: int
name: str
book: Book = {"id": 123, "name": "To Kill A Mockingbird"}
However this syntax doesn't work if any keys aren't valid identifiers - perhaps they contain a period .
or a hyphen -
:
from typing import TypedDict
class Book(TypedDict):
id: int
name: str
some-hyphen-field: str
field.dot: str
In this case you can use the functional syntax:
from typing import TypedDict
Book = TypedDict(
'Book',
{
"id": int,
"name": str,
"some-hyphen-field": str,
"field.dot": str
}
)