Python Type Hints: Declaring Static Types for Readable Code

What is Python Type Hinting?

Type hints in Python are optional annotations that declare the expected types of variables and function parameters. They improve readability, help other developers understand your code, and allow static type checkers to identify potential type mismatches.

Why Use Type Hinting?

Type hints help to catch errors early by enforcing consistency in data types. For example, when developing software to calculate monthly expenses in a Filipino household, specifying the type of each input variable as float or int can prevent issues if someone mistakenly inputs an incompatible type.

Syntax

  • Use variable: type to annotate variables.
  • For functions, define define def function (parameter: type) -> return_type.
variable: type
def function(parameter: type) -> return_type:
    # Code block

Example

Let’s say you want to calculate the average expense of a Filipino Family and want to ensure proper type you can do it with type hints.

from typing import List

# Function to calculate the average monthly expense of a Filipino family
def calculate_average_expense(expenses: List[float]) -> float:
    # Print the type of the parameter 'expenses'
    print("Type of 'expenses' parameter:", type(expenses))
    
    # Calculate the average expense
    average = sum(expenses) / len(expenses)
    
    # Print the type of the calculated 'average'
    print("Type of 'average' result:", type(average))
    
    return average

# Sample monthly expenses in pesos
monthly_expenses = [10000.0, 12000.0, 11500.0, 10500.0, 11000.0]

# Print the type of 'monthly_expenses' before passing to function
print("Type of 'monthly_expenses' variable:", type(monthly_expenses))

# Calculate and print the average monthly expense
average_expense = calculate_average_expense(monthly_expenses)
print("Average Monthly Expense:", average_expense)  # Expected output: 11000.0

Scroll to Top