How to use Dict to specify type-hint in Python

Question:

I have a function which will return a dictionary like:

from typing import Dict

def foo() -> Dict[]:
    params = {
        "side": "Buy",
        "symbol": "BTCUSDT",
        "order_type": "Market",
        "time_in_force": "PostOnly",
        "reduce_only": False,
        "close_on_trigger": False,
    }
    return {
        "method": "POST",
        "api": "private/linear/order/create",
        "body": params
    }

What should be the content inside Dict[]?

Asked By: tung

||

Answers:

It would be something like this Dict[str, Union[str, Dict]]. The first argument is for the type of the key of the dictionary and the second is the type of the value. In this case, it is non-homogeneous so we need a Union to describe it.

Answered By: Savio Joanes

If the keys of your dictionary are all string and fixed, the TypedDict in Python3.8+ is very suitable here:

from typing import TypedDict


class Params(TypedDict):
    side: str
    symbol: str
    order_type: str
    time_in_force: str
    reduce_only: bool
    close_on_trigger: bool


class Foo(TypedDict):
    method: str
    api: str
    body: Params


def foo() -> Foo:
    params: Params = {
        "side": "Buy",
        "symbol": "BTCUSDT",
        "order_type": "Market",
        "time_in_force": "PostOnly",
        "reduce_only": False,
        "close_on_trigger": False,
    }
    return {
        "method": "POST",
        "api": "private/linear/order/create",
        "body": params
    }
Answered By: Mechanic Pig