trite.io - posts

Adventures in Python static type checking

Created: January 18, 2022

Coming back to Python this weekend for a job interview has gone from fun nostalgia to full-blown learning adventure. I haven’t touched Python much in the last 3 years. My recent time has been spent heavily focusing on Functional Programming concepts, lots of Haskell and F#.

These are some notes and things of interest.

Type Checker – MyPy vs Pyright vs Pytype vs Pyre

PEP 484 gave Python support for static type checking. This is of course an opt-in feature, since Python’s default type system is dynamic duck (quack). After several hours and 3 advent of code problems I sat down and started looking at what would be involved.

It’s really quite easy to get setup with either MyPy or Pyright. Pytype and Pyre are on the list to check out eventually.

MyPy

http://mypy-lang.org/

Started to check out MyPy briefly, but the pattern matching added in Python 3.10 was not yet supported by it. This cut things pretty short.

Pyright/Pylance

Pyright appears to be Microsoft’s stab at type checking, while Pytype and Pyre look to be Google and Facebook’s respectively:

Pylance is a VSCode extension providing lots of intellisense QoL and other neat features for developing Python: https://marketplace.visualstudio.com/items?itemName=ms-python.vscode-pylance

Activating typechecking in Pylance:

Once activated you’ll either be greeted by basically nothing changing if your code is already compliant, or by a spectacular wall of errors and warnings to fix. The wall of errors version is intimidating at first, but it should require considerably fewer code changes than it seems. Most of those changes are likely just type annotations, not modifying actual code behavior.

TODO: expand on these later