Today we’re going to talk about something that’ll make your code look like a boss. We’re talking about Python annotations the coolest thing since sliced bread (or maybe even better).
If you haven’t heard of them before, let me break it down for ya: Annotations are basically little hints or notes that you can add to your code to tell Python what type a variable should be. It’s like adding a little post-it note next to each line saying “hey, this is supposed to be an integer!”
Now, I know what some of you might be thinking: “But wait, isn’t that just redundant? Can’t Python figure out the type on its own?” And the answer is…kinda. But sometimes it can get confused or make mistakes (especially if you have a lot of nested functions and variables). Plus, having annotations makes your code more readable for other people who might be looking at it later on.
So how do we add these little post-it notes to our code? Well, let’s take a look at some examples:
# This function takes in a list of integers and returns the sum of all the numbers in the list.
def calculate_sum(numbers: List[int]) -> int:
# Initialize a variable to store the total sum.
total = 0
# Loop through each number in the list.
for num in numbers:
# Add the current number to the total sum.
total += num
# Return the final total sum.
return total
In this example, we have added annotations to the function parameters and return type. The `List[int]` part means that the `numbers` parameter should be a list of integers (you can also use other data types like str or float). And the `-> int` part at the end tells Python what type the function will return in this case, an integer.
Now let’s say you have some code that looks like this:
# This function takes in a list of integers and calculates the average of all the numbers in the list.
def calculate_average(numbers: List[int]) -> int:
# Initialize a variable to keep track of the total sum of all the numbers in the list.
total: int = 0
# Loop through each number in the list.
for num in numbers:
# Add the current number to the total sum.
total += num
# Calculate the average by dividing the total sum by the length of the list.
average: int = total / len(numbers)
# Return the calculated average.
return average
This code works fine, but it doesn’t have any annotations. If you want to add them later on (or if someone else is working on the same project and wants to use a static analysis tool), they might not know what type `numbers` should be or what type the function will return. This can lead to errors and confusion down the line.
But with annotations, it’s much clearer:
# This function takes in a list of integers and returns the average as a float
def calculate_average(numbers: List[int]) -> float:
# Initialize a variable to store the total sum of the numbers
total = 0
# Loop through each number in the list
for num in numbers:
# Add the current number to the total sum
total += num
# Calculate the average by dividing the total sum by the length of the list
average = total / len(numbers)
# Return the average as a float
return average
Now, if you run this code through a static analysis tool like Mypy (which we’ll talk about later), it will check to make sure that `numbers` is indeed a list of integers and that the function returns a float. If there are any errors or discrepancies, Mypy will let you know right away so you can fix them before they cause bigger problems down the line.
So why should you use annotations instead of type comments? Well, for one thing, annotations provide a cleaner syntax that keeps type information closer to your code. They’re also officially recommended by Python and will be further developed and properly maintained in the future. Type comments are more verbose and might conflict with other kinds of comments in your code like linter directives . However, they can be used in code bases that don’t support annotations.
But what if you have a library or package that doesn’t support annotations? That’s where stub files come in these are special files that contain type hints for functions and variables that aren’t defined in your own codebase. They can be used to add type hints to existing code that doesn’t lend itself to adding type hints, like 3rd party packages or extension modules.
With these little post-it notes, your code will look more readable and professional, and static analysis tools can help catch errors before they cause bigger problems down the line.