brettcannon · GitHub

All major type checkers now support recursive type aliases by default, so this should largely work:

JSON: TypeAlias = dict[str, "JSON"] | list["JSON"] | str | int | float | bool | None

Note that because dict is invariant, you might run into some issues e.g. with dict[str, str]. That is, you will not be able to pass something with type dict[str, str] to a function that takes a JSON

For such use cases you can use cast, and if you don't need mutability, something like the following might work:

JSON_ro: TypeAlias = Mapping[str, "JSON_ro"] | Sequence["JSON_ro"] | str | int | float | bool | None

Although this can sometimes result in false negatives, for instance, see python/mypy#13786 (comment)

Read the original on github.com ↗