Functional Annotations in Python 3.x

Have you used Functional Annotations in Python 3.x? Maybe you’ve heard them mentioned? Regardless, let’s explore what they are and how they help us. Because if they don’t help us, then we probably shouldn’t care.

The Problem

  1. You’re programming and don’t know what thisRandomFunction should return. Maybe it’s a bool maybe it’s a string who knows?
  2. Does the output value of my function match what we expect?

What Functional Annotations Look Like

So what are functional annotations? They look like this:

->

But they’re added to the butt end of a function like this:

def fake_function() -> bool:
    return True

Now when you look to use the function it is completely obvious what you should expect back. You might even decide to use the function with an if statement like this:

if fake_function():
    print('it was fake')
else:
    print('not fake')

I Was Surprised to Find

I was surprised to find that Python didn’t enforce these functional annotations out of the box. You could define a function like so without getting Python itself to throw an error.

def another_test_function()->'cheese':
    return False

another_test_function()

But if we take a step back and consider Typescript. From my rudimentary understanding Typescript itself doesn’t enforce return types, it’s another piece of software layered ontop that does the enforcement. So I guess I need to do more exploration on ts-lint Python equivalents? I imagine these annotations are also leveraged by our IDEs to inform us when we’re making mistakes.

So Why Use Functional Annotations in Python 3.x?

Functional annotations should be used to help you deciper what thatOneRandomFunction does. It’ll also help your IDE tell you when you’ve made a mistake. This might not be a problem on smaller projects with just a few functions, but I imagine it makes bug bashing on larger Python scripts much easier. I’ve experienced similar returns on investment while developing with Typescript and defining my input and return types. We have to remember that while Python is great for small quick and dirty jobs, projects like Flask are being used to throw together entire apps from top to bottom.

Do you need functional annotations on smaller projects? No, you can probably get by. Should you add them? Why not start? It might help your project in the long run.

Don’t know where to schedule your Python scripts or ETL pipelines? Check this article out which covers setting up Airbnb’s Apache Airflow.

Leave a Comment