I want to type hint the return object of some_func function, which is always the same format. Is this correct?
from typing import List, Dict
def some_func() -> List[Dict[str, int, str, List[CustomObject]]]:
my_list = [
{"ID": 1, "cargo": [CustomObject(), CustomObject()]},
{"ID": 2, "cargo": [CustomObject(), CustomObject()]},
{"ID": 2, "cargo": [CustomObject(), CustomObject()]}
]
return my_list
You can do this with a TypedDict:
class MyDict(TypedDict):
ID: int
cargo: list[CustomObject]
def some_func()->list[MyDict]:
pass
A typed dict, see PEP 589 is a way to specify different types for different keys in a dict.
Also note that since python 3.10 you can just use list[type] instead of typing.List[type]. Works for dicts and tuples too.
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