How can I add type hints to a small function's parameters and return value?
Quick answer
Put a colon and type after each parameter name, then write an arrow and the return type after the closing parenthesis. For example: def greet(name: str) -> str:. Choose annotations that describe the values the function expects and the value it returns. In Python, annotations communicate those expectations to readers and tools; they do not automatically check calls or returned values at runtime. [S1]
The question, the details, the next step.
A practical checklist
Add
: typeafter each parameter name you want to describe.Put the intended return type after
->and before the definition’s final colon.Check every return path so the return annotation matches the function’s behavior.
Use annotations to communicate expectations, not as automatic runtime validation.
Handle any separate tool or runtime-check requirements separately.
A few more useful answers
Do type hints automatically prevent a caller from passing the wrong kind of value?
No. Python does not enforce function annotations at runtime. Type checkers, IDEs, and linters may use hints to help identify mismatches. [S1]
What does the arrow in a function signature mean?
The -> introduces the annotated return type. For example, def greet(name: str) -> str: describes an expected string parameter and an intended string return value. [S1]
Sources
References used for this guide.
- [S1] Python typing — Support for type hints docs.python.org · Checked
