How to Use Basic Type Hints (int, str) for Return Values in Python
Declare a simple function with int and str type hints and a typed return value in Python.
Python code
6 linesdef greet(name: str, age: int) -> str:
return f"{name} is {age} years old."
if __name__ == "__main__":
print(greet("Alice", 30))
Output
Alice is 30 years old.
How it works
Type hints are annotations that tell developers (and tools like mypy) what types a function expects and returns. Here, name: str and age: int mark the parameters, and -> str marks the return type. Although Python does not enforce these hints at runtime, they make code self-documenting and enable static type checking and IDE autocompletion.
This simple pattern is the foundation for writing maintainable, typed Python code. The if __name__ == "__main__": guard ensures the test call runs only when the script is executed directly.
Common mistakes
- Forgetting to add the return type annotation (-> str) after the closing parenthesis.
- Using mutable defaults (like `list=[]`) with type hints, which can cause shared-state bugs.
- Assuming type hints enforce runtime checks; they don't — use a linter like mypy for that.
Variations
- Use optional hints: `def greet(name: str, age: int | None = None) -> str:`
- Use `from __future__ import annotations` to defer evaluation of type hints.
- Add `from typing import Any` and use `Any` when type is unknown.
Real-world use cases
- Defining API response formatters where the return type is guaranteed to be a string.
- Building small utilities that log or format user info with typed parameters.
- Writing test helpers that need clear input and output contracts for readability.
Sponsored
More from Testing & modern typing
- Capture stdout and stderr with pytest capsys easy
- Characterization Test for Legacy Python Code medium
- Dataclass with Type Hints Fields in Python easy
- Dependency Injection in Python for Testability easy
- Design Data Helpers with Python TypedDict and Literal easy
- Fix and Test a Regression Bug in Python with Unit Tests easy
Keep learning
Related tutorials and quizzes for this topic.