Make your Python code more readable with Python 3.9

Sagar Vakkala
The Zeals Tech Blog
3 min readDec 10, 2021

I’ve seen a lot of supposedly clean “Annotated” Python codebases hard to read and use as a software engineer. Complex python applications get filled up with Verbose annotations with no metadata. It goes both ways. As hard it is to use complex codebases, It’s also hard maintaining them to be readable as well.

I want to talk about the struggles with maintaining a readable Python code base (even with annotations) and how Python 3.9‘s new Annotation features can push us in the right direction to make sure that our Python codebases become more readable (and maintainable).

Let’s look at a simple example:

This is good. As a dev calling this method, we know that get_velocity() requires two parameters: distance and time. But, We don’t know the meta information of the parameters being supplied, In this case, it would be:

  • Distance: What kind? In meters? Feet?
  • Time: In seconds? Minutes? Hours?

You could argue and say that Sagar, We can mention it in the function’s docstring. Something like this:

True, but this doesn’t specifically increase my readability of the code. Let me explain, We still have to glance over the docstring to understand the param definition. Our goal today is to increase the readability of our code to the highest degree possible.

In came PEP 484. PEP 484 suggested that annotations should be used for type hints (really nice!). With this, PEP 593 got introduced into Python 3.9, and it was suggested that we can combine type hints with more arbitrary metadata!

Let’s redo the above example with PEP 593:

“Annotated” takes at least two arguments. The first argument is a type hint and the rest of the arguments are metadata.

You can access the annotations through .__annotations__ as usual.

>>> from calc import get_velocity
>>> get_velocity.__annotations__
{'distance': typing.Annotated[float, 'meters'], 'time': typing.Annotated[float, 'seconds'], 'return': <class 'float'>}

Looks pretty good so far. But, “Annotated” is making our code a little verbose, We need to shorten it down. You can do it using type aliases.

It’s shaping up pretty well now. Our annotations are carrying all the metadata we’d need for good code readability. Now, Let’s shift these type-aliases to another file.

We have now made our get_velocity function more readable by adding more metadata and decreased the verbosity of code by using type aliases.

If you haven’t made the jump over to Python 3.9 yet, I hope this further encourages you to do so.

--

--