How to Use Typing Module to Annotate Function Definition with Input and Output Types in Python
Pavol Z. Kutaj

Pavol Z. Kutaj @pkutaj

About: A public interface of my current learnings. The focus is on everything from vim, python to cloud. Imperfect. Impersonal. Never too far from my terminal.

Location:
Brno, Czech Republic
Joined:
Jan 26, 2021

How to Use Typing Module to Annotate Function Definition with Input and Output Types in Python

Publish Date: Dec 17 '24
0 0

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
Enter fullscreen mode Exit fullscreen mode

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

Comments 0 total

    Add comment