Home > Backend Development > Python Tutorial > How to Use Typing Module to Annotate Function Definition with Input and Output Types in Python

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

Barbara Streisand
Release: 2024-12-21 13:43:11
Original
409 people have browsed it

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.
    • See more: https://peps.python.org/pep-0484/#the-typing-module
  • 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
Copy after login

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#(part._sec~3adesign-func)

The above is the detailed content of How to Use Typing Module to Annotate Function Definition with Input and Output Types in Python. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template