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.

Easy Python 3.9+ Aug 9, 2026 Testing & modern typing 12 views 0 copies

Python code

6 lines
Python 3.9+
def greet(name: str, age: int) -> str:
    return f"{name} is {age} years old."


if __name__ == "__main__":
    print(greet("Alice", 30))

Output

stdout
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

  1. Use optional hints: `def greet(name: str, age: int | None = None) -> str:`
  2. Use `from __future__ import annotations` to defer evaluation of type hints.
  3. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Testing & modern typing

Related tutorials and quizzes for this topic.