I am adding type annotations to a lot of code to make it clear to other devs what my functions and methods do. How would I type annotate a function that takes JSON data in as an argument, and returns JSON data?
(very simplified version)
def func(json_data):
return json_data
what I want to do but with JSON instead of int:
def add_nums(a: int, b: int) -> int:
return a+b
Quoting from https://github.com/python/typing/issues/182#issuecomment-1320974824:
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 | NoneNote that because
dictis invariant, you might run into some issues e.g. withdict[str, str]. For such use cases you can usecast, 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With