Add Type Hints to Function Parameters and Return in Python
Add type hints to function parameters and return values in Python for clearer, more maintainable code using the typing module.
Python code
23 linesfrom typing import List, Optional, Dict
def average(numbers: List[float]) -> float:
return sum(numbers) / len(numbers)
def full_name(first: str, last: Optional[str] = "") -> str:
return f"{first} {last}".strip()
def build_user(name: str, age: int, email: Optional[str] = None) -> Dict[str, object]:
user = {"name": name, "age": age}
if email:
user["email"] = email
return user
if __name__ == "__main__":
nums = [10.5, 20.0, 30.25]
print(f"Average: {average(nums)}")
print(f"Full name: {full_name('Jane', 'Doe')}")
print(f"User: {build_user('Bob', 30, 'bob@example.com')}")
Output
Average: 20.25
Full name: Jane Doe
User: {'name': 'Bob', 'age': 30, 'email': 'bob@example.com'}
How it works
Type hints allow you to document the expected types of function parameters and return values directly in the code. The typing module provides generic types like List, Dict, and Optional for more precise annotations. Using Optional[str] indicates the parameter can be a string or None. Type hints are not enforced at runtime, but tools like mypy and IDEs use them for static checking and autocomplete.
Common mistakes
- Using `List` and `Dict` without importing from `typing` in older Python versions
- Forgetting that `Optional[str]` is shorthand for `Union[str, None]`
- Assuming type hints enforce type checking at runtime
- Using lowercase `list` and `dict` in Python versions before 3.9
Variations
- Use built-in generics like `list[float]` and `dict[str, object]` with Python 3.9+
- Use `from __future__ import annotations` to defer evaluation of annotations
Real-world use cases
- Documenting function contracts in a shared library or SDK for other developers.
- Enabling static type checking in CI pipelines to catch type mismatches before deployment.
- Improving IDE autocomplete and refactoring safety for large codebases.
Sponsored
More from Functions & basics
- Benchmark list append vs comprehension in Python easy
- Build a Context Manager in Python with contextlib.contextmanager easy
- Build a Progress Callback Function for Loops in Python easy
- Cache expensive function with lru_cache in Python easy
- Calculate Time Difference Across Time Zones in Python easy
- Call a Function Dynamically by Name in Python easy
Keep learning
Related tutorials and quizzes for this topic.