7. Function Annotations

These examples demonstrate how function annotations can be used to improve code readability, documentation, and static analysis. Although Python itself doesn’t enforce type annotations at runtime, tools like mypy can use these annotations for type checking.


1. Basic Function Annotations

def greet(name: str) -> str:
    return f"Hello, {name}!"

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

2. Annotating Multiple Arguments

def add(x: int, y: int) -> int:
    return x + y

print(add(10, 20))  # Output: 30

3. Using Annotations with Default Values

def power(base: int, exponent: int = 2) -> int:
    return base ** exponent

print(power(5))       # Output: 25
print(power(5, 3))    # Output: 125

4. Annotations for Custom Types


5. Annotations for Optional Parameters


6. Annotations for Callable Objects


7. Annotations with Dictionaries


8. Annotations with Tuples


9. Annotations for Generator Functions


10. Accessing Function Annotations


Last updated