Type Hints and Annotations

Type hints and annotations are features in Python that allow developers to indicate the expected data types of function arguments, return values, and variables. They improve code readability and help tools like linters and IDEs catch type-related errors during development.


Basic Syntax

Annotating Function Arguments

You can specify the type of a function argument by using a colon (:) followed by the type.

def greet(name: str):
    print(f"Hello, {name}!")

Annotating Return Types

Use -> to specify the return type of a function.

def add(a: int, b: int) -> int:
    return a + b

Combining Argument and Return Type Hints

def concat_strings(a: str, b: str) -> str:
    return a + b
Info

Type hints are optional and do not enforce type checking at runtime. They are used for static analysis and better code clarity.


Using typing Module

The typing module provides additional tools for complex type annotations.

Common Types

  1. List
from typing import List

def sum_list(numbers: List[int]) -> int:
    return sum(numbers)
  1. Tuple
from typing import Tuple

def get_coordinates() -> Tuple[int, int]:
    return (10, 20)
  1. Dict
from typing import Dict

def count_fruits() -> Dict[str, int]:
    return {"apple": 10, "banana": 20}
  1. Union (Multiple Possible Types)
from typing import Union

def process_value(value: Union[int, str]) -> str:
    return str(value)
  1. Optional (Nullable Types)
from typing import Optional

def find_item(item_id: int) -> Optional[str]:
    if item_id == 1:
        return "Item Found"
    return None
Deep Dive

Using typing is essential for complex type definitions, especially when working with collections or mixed types.


Type Aliases

Create aliases for commonly used type definitions to improve readability.

from typing import List

# Define a type alias
UserIDList = List[int]

def get_user_ids() -> UserIDList:
    return [1, 2, 3, 4]

File Structure Example

project/
├── main.py
└── utils.py
Task

Practice: Implement Type Hints

Objective: Add type hints to the following functions.

  1. Function Without Hints:
def multiply(a, b):
    return a * b
  1. Add Type Hints:
def multiply(a: int, b: int) -> int:
    return a * b
  1. Implement Complex Types:

Define a function that takes a list of strings and returns a dictionary of string counts.

from typing import List, Dict

def count_words(words: List[str]) -> Dict[str, int]:
    result = {}
    for word in words:
        result[word] = result.get(word, 0) + 1
    return result
Under Construction

Consider using type hints in all functions for better clarity and integration with modern IDEs and tools.

Copyright © 2025 Devship. All rights reserved.

Made by imParth