How can I type-hint a nested object in Python?

Updates derived from conversation in comments

  1. You will need each class to be a subclass of TypedDict. Something like class Foo(TypedDict).
  2. errorUUID is an Optional[str].
  3. accounts is type Dict[str, List[AccountType]] since it has an inner (perhaps redundant) key also called accounts.
  4. You need to use square brackets with stringified keys to access the keys - accountsResponse['accounts']['accounts'].

Here is a proposed solution:

from typing import List, TypedDict, Optional, Dict

class MethodResultType(TypedDict):
    code: str
    description: str
    errorUUID: Optional[str]

class AccountType(TypedDict):
    accountId: int
    accountName: str
    availableCredit: float

class getAccounts(TypedDict):
    result: MethodResultType
    accounts: Dict[str, List[AccountType]]

result: getAccounts = {
    'result': {
        'code': '1',
        'description': 'Success',
        'errorUUID': None
    },
    'accounts': {
        'accounts': [
            {
                'accountId': 1,
                'accountName': 'Ming',
                'availableCredit': 1
            }
        ]
    }
}

See this MyPy playground: https://mypy-play.net/?mypy=latest&python=3.8&gist=dad62a9e2cecf4bad1088a2636690976

TypedDict is an extension to MyPy, make sure to install MyPy (plus extensions) and import TypedDict: from typing_extensions import TypedDict.

From Python 3.8 you can import TypedDict directly from the typing module.

https://mypy.readthedocs.io/en/latest/more_types.html#typeddict https://www.python.org/dev/peps/pep-0589/