To set the stage: what are annotations? Well, they’re basically type hints on juice. Instead of just saying “this function takes in an integer”, you can say “this function takes in an int” (with the added benefit of Mypy catching any errors if you accidentally pass a string instead).
So how do we use this magical feature? Let’s take a look at some examples:
# This function takes in two integers and returns an integer as the sum of the two numbers
def add_numbers(a: int, b: int) -> int:
"""Add two numbers together"""
return a + b
See that little colon and arrow after the function signature? That’s where the magic happens. The `int` annotations tell Mypy (and other tools) what types of data we expect to be passed in, while the `-> int` tells us what type of data will be returned.
But wait there’s more! You can also add annotations to variables:
# The function below calculates the sum of all integers in a given list of numbers.
# It takes in a list of numbers as input and returns an integer as output.
def calculate_sum(numbers: list) -> int: # Function signature with annotations for input and output types
total: int = sum([x for x in numbers if isinstance(x, int)]) # Variable annotation for total, using sum() to calculate the sum of all integers in the list
return total # Return statement with annotation for the returned data type
In this example, we’re using a list comprehension to filter out any non-integer values from the `numbers` input. But what happens if someone accidentally passes in a string instead? Mypy will catch it and let us know that something is wrong!
So why should you use annotations? Well, for starters, they make your code more readable (especially when paired with docstrings). They also help catch errors early on, which can save you a ton of time in the long run. And if you’re working on a team project, having consistent type hints throughout your codebase can be incredibly helpful for everyone involved!
But here’s the thing: annotations aren’t perfect. They can sometimes get in the way (especially when dealing with complex data structures), and they don’t always play nicely with other tools or libraries. So use them sparingly, and only where it makes sense to do so.