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
Copy
def add_numbers(a: int, b: int) -> int:
return a + b
result = add_numbers(5, 10)
print(result) # Output: 152. Type Hinting with Optional Arguments
Copy
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
Copy
4. Type Hints for Dictionaries
Copy
5. Type Hints for Tuples
Copy
6. Type Hints for Callable (Functions as Arguments)
Copy
7. Type Hints for Iterables
Copy
8. Custom Types
Copy
9. Union for Multiple Accepted Types
Copy
10. Type Hints for Generators
Copy
Last updated