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, too

1. Basic Function Annotations

Copy

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

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

2. Annotating Multiple Arguments

Copy

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

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

3. Using Annotations with Default Values

Copy

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

Copy


5. Annotations for Optional Parameters

Copy


6. Annotations for Callable Objects

Copy


7. Annotations with Dictionaries

Copy


8. Annotations with Tuples

Copy


9. Annotations for Generator Functions

Copy


10. Accessing Function Annotations

Copy


Last updated