Type Hinting (PEP 484)
Python is dynamically typed, but modern Python encourages type hinting—adding optional annotations that suggest the expected data type for parameters and return values.
Type hints do not affect the program's execution (Python still checks types at runtime), but they significantly improve code readability, documentation, and enable powerful static analysis tools (like linters and IDEs).
Basic Syntax
Use a colon : after the parameter name, followed by the expected type. Use -> followed by the expected return type.
python def greeting(name: str) -> str: return f"Hello, {name}"
Function call remains the same
print(greeting("Dana"))
Type Hinting for Standard Structures
For complex structures like lists and dictionaries, use types from the typing module (or standard types in Python 3.9+).
python from typing import List, Dict
def get_high_scores(scores: List[int]) -> float: """Calculates the average of high scores.""" return sum(scores) / len(scores)
def print_user_info(user: Dict[str, str]) -> None: # Use 'None' if the function doesn't explicitly return anything print(f"User Name: {user['username']}")
get_high_scores([90, 85, 92])
Using type hints is a hallmark of professional Python code, making it easier for teammates (or your future self) to understand the function's contract.