Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type annotation for dict arguments [duplicate]

Tags:

python

Can I indicate a specific dictionary shape/form for an argument to a function in python?

Like in typescript I'd indicate that the info argument should be an object with a string name and a number age:

function parseInfo(info: {name: string, age: number}) { /* ... */ }

Is there a way to do this with a python function that's otherwise:

def parseInfo(info: dict):
  # function body

Or is that perhaps not Pythonic and I should use named keywords or something like that?

like image 391
Jonathan Tuzman Avatar asked Mar 07 '26 11:03

Jonathan Tuzman


1 Answers

In Python 3.8+ you could use the alternative syntax to create a TypedDict:

from typing import TypedDict

Info = TypedDict('Info', {'name': str, 'age': int})


def parse_info(info: Info):
    pass

From the documentation on TypedDict:

TypedDict declares a dictionary type that expects all of its instances to have a certain set of keys, where each key is associated with a value of a consistent type. This expectation is not checked at runtime but is only enforced by type checkers.

like image 72
Dani Mesejo Avatar answered Mar 09 '26 02:03

Dani Mesejo



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!