This guide explains function annotations: syntax and practical use through a focused Python example. You will learn the behavior to expect, why it matters in a real program, and how to recognize the common mistakes before applying it in your own project.
What You Will Learn
Function annotations record expected parameter and return types for readers and type checkers. Python generally does not enforce those types automatically when a function runs.
When and Why to Use It
The following example focuses on a practical use of Function Annotations: Syntax and Practical Use.
Step-by-Step Example
def calculate_total(price: float, quantity: int) -> float:
return price * quantity
print(calculate_total(4.5, 3))
print(calculate_total.__annotations__)
Understanding the Example
The call returns 13.5. __annotations__ exposes metadata, although the exact representation of annotation values depends on evaluation settings and runtime.
Expected Output
13.5
{'price': 'float', 'quantity': 'int', 'return': 'float'}
Important Behavior and Edge Cases
Type hints cannot replace runtime validation, especially for input from users, files and networks.
Try It Yourself
Annotate a function that accepts a string and returns its character count.
Common Beginner Mistakes
- Type hints cannot replace runtime validation, especially for input from users, files and networks.
- Confusing a returned value with printed output, or failing to verify a function’s behavior with different input values.
- Skipping the practice step and assuming the example covers every input. Test at least one normal case and one edge case relevant to this topic.
Key Takeaways
- Function annotations record expected parameter and return types for readers and type checkers.
- The call returns 13.5.
- Apply the technique deliberately, checking its documented input requirements and failure behavior before integrating it into a larger project.