Python Supports Type Annotations Now!
Author: Alyssa Riceman
Posted:
This week, I returned to Python for the first time in A While. And I discovered something wonderful and beautiful which was a continual source of delight to me throughout the week: as of Python 3.9, Python now supports type annotations!
Being Python, of course, it’s supporting them in a weird Python-y way. They’re officially called ‘type hints’, because unlike traditional type annotations, they’re only there for humans; the interpreter doesn’t care the slightest bit about them. You can throw a dict
into a function marked as taking in a str
, or return a bool
from a function marked as returning a tuple[int, int]
, or whatever else, and it’ll function just as it would with no type annotations at all.
But, even if the interpreter doesn’t care, I, as a person who needs to interact with the source code, care a lot. The type annotations make it so much faster to figure out what I’m supposed to do with unfamiliar functions or methods, as compared with reading the docs (if I’m lucky and the docs are clear on the matter) or trial-and-error testing (if I’m less lucky).
(They also make it all the more conspicuously inconvenient, when a given library happens not to have implemented type annotations in its code yet and so I am still forced to do those things.)
For that matter, even when working with familiar code and functions, the annotations still end up being useful, just for the way they put type information right at my metaphorical fingertips such that I don’t need to rely on memory so much. When I hover over a variable name in VSCode, now, the IDE will let me know what type that variable is to the best of its ability to figure out, saving me the trouble of rereading the code which produced that variable to make sure it’s the right type.
Overall, this is an excellent change, and I’m glad it’s happened.
Tags: Python