The aim of this pageđź“ť is to explain how to use type hints in Python, specifically for functions that return a list of dictionaries.
I am slowly going through David Baezley's Advanced Python mastery and - based on How to Code's systematic approach to program design - I am annotating functions with input and output types as that definition determines the shape of the function.
- Type hints: Improve code readability and maintainability.
-
typing
module: Provides more specific type annotations. - PEP 484: Introduced type hints in Python 3.5.
-
Common types:
List
,Dict
,Tuple
,Union
,Optional
. -
Specify list of dicts: Use
List[Dict[str, int]]
for return type. -
Example from Advanced Python Mastery which reads a provided
.csv
files with Bus timetable of four columns and returns a list of dictionaries. Mostly, I want to specify that latter fact.
from typing import List, Dict
import csv
def read_rides(filename: str) -> List[Dict]:
rides = []
with open(filename, "r") as file:
rows = csv.reader(file)
headers = [row.strip() for row in next(rows)]
print(f"ROW headers: {headers}")
for row in rows:
ride = {}
for column_number, column_name in enumerate(headers):
ride[column_name] = row[column_number].strip()
rides.append(ride)
return rides
LINKS
https://peps.python.org/pep-0484/#the-typing-module
https://github.com/dabeaz-course/python-mastery/blob/main/Exercises/ex2_2.md
https://htdp.org/2022-2-9/Book/part_one.html#%28part._sec~3adesign-func%29
Top comments (0)