Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would you type hint Dict in Python with constant form but multiple types?

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
like image 858
M.wol Avatar asked Oct 28 '25 22:10

M.wol


1 Answers

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.

like image 175
mousetail Avatar answered Oct 31 '25 12:10

mousetail



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!