1. Typing Module
Leveraging Python's type hints to improve code readability and static analysis
1. Specifying Function Input and Output Types
from typing import List
def sum_of_integers(numbers: List[int]) -> int:
return sum(numbers)
print(sum_of_integers([1, 2, 3])) # Output: 62. Using Optional for Nullable Parameters
from typing import Optional
def greet(name: Optional[str] = None) -> str:
if name:
return f"Hello, {name}!"
return "Hello, Guest!"
print(greet()) # Output: Hello, Guest!
print(greet("Alice")) # Output: Hello, Alice!3. Type Hint for Dictionaries
4. Using Union for Multiple Types
5. Custom Type Aliases
6. Using Callable for Functions
7. Using Tuple for Fixed-Length Sequences
8. Using Any for Flexible Input
9. Using Literal for Specific Values
10. Using TypedDict for Structured Dictionaries
Last updated