97. Function Annotations for Type Hints

Here are 10 Python code snippets demonstrating function annotations for type hints to improve code clarity and documentation:


1. Basic Type Hints for Arguments and Return Types

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

result = add_numbers(5, 10)
print(result)  # Output: 15

2. Type Hinting with Optional Arguments

from typing import Optional

def greet(name: Optional[str] = None) -> str:
    return f"Hello, {name if name else 'Guest'}!"

print(greet())           # Output: Hello, Guest!
print(greet("Alice"))    # Output: Hello, Alice!

3. Type Hints for Lists

from typing import List

def calculate_average(numbers: List[float]) -> float:
    return sum(numbers) / len(numbers)

print(calculate_average([1.5, 2.5, 3.0]))  # Output: 2.3333333333333335

4. Type Hints for Dictionaries


5. Type Hints for Tuples


6. Type Hints for Callable (Functions as Arguments)


7. Type Hints for Iterables


8. Custom Types


9. Union for Multiple Accepted Types


10. Type Hints for Generators


These examples illustrate how type hints improve code readability and provide valuable documentation, helping developers understand the expected types of arguments and return values. Although type hints don’t enforce types at runtime, they enhance static analysis and integrate seamlessly with tools like mypy for type checking.

Last updated