I'm trying to declare the type of the output for a function and it is a list of dictionaries. How can I declare it in the function definition?
x = [['book', 55], ['magazine', 30]]
def my_function(x: list) -> list:
return [{f'{i[0]}: {i[1]}'} for i in iter(x)]
print(my_function(x))
[{'book: 55'}, {'magazine: 30'}]
CodePudding user response:
You can use the typing module for this (and possibly list
and dict
directly in the most recent versions of Python):
from typing import List, Dict
def my_function(x: list) -> List[Dict[str,str]]:
CodePudding user response:
To specify what type is contained in a container, you can use the subscript operator. For example:
def my_function(x: list[typing.Any]) -> list[dict[str, str]]:
...
Note that this syntax is only valid starting with Python 3.9. If you are on an older version, you have to instead use the type aliases defined in the typing
package:
def my_function(x: typing.List[typing.Any]) -> typing.List[typing.Dict[str, str]]:
...