DEV Community

Pavol Z. Kutaj
Pavol Z. Kutaj

Posted on

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

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

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

đź‘‹ Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay