Python Type Hints - How to Create a TypedDict with Non-Identifier Keys

Some kind of widget used by a typographer.

Using TypedDict is a great way to type code that passes around dictionaries. The default way to create a TypedDict is with its class-based syntax:

import datetime as dt
from typing import TypedDict


class Event(TypedDict):
    date_time: dt.datetime

This syntax works great for most use cases, but is not possible for dictionaries with keys that aren’t valid Python identifiers (variable names). Such keys may be used if the dict is not created in our system, but e.g. from calling a third-party API.

For example, imagine if we needed to use the key "date-time" instead of "date_time" above. We could try defining this in a class:

import datetime as dt
from typing import TypedDict


class Event(TypedDict):
    date - time: dt.datetime

However this triggers a SyntaxError:

$ python example2.py
  File "/.../example.py", line 6
    date-time: dt.datetime
    ^
SyntaxError: illegal target for annotation

Python parses date-time as an expression, meaning “date minus time”. The type hint following the expression is not allowed.

To create this TypedDict, we need to instead turn to its function-based syntax:

import datetime as dt
from typing import TypedDict

Event = TypedDict("Event", {"date-time": dt.datetime})

We can use any string as a key in a TypedDict like this.

Fin

May your dicts always be type checked,

—Adam


Make your development more pleasant with Boost Your Django DX.


Subscribe via RSS, Twitter, Mastodon, or email:

One summary email a week, no spam, I pinky promise.

Related posts:

Tags: ,