DEV Community

Konstantin Sofeikov
Konstantin Sofeikov

Posted on

Static shape checking for NumPy: one mypy plugin, precise shapes before anything runs

GitHub logo sofeikov / numty

Static shape checking for NumPy: one mypy plugin, precise shapes before anything runs

numty

Static shape checking for NumPy.
Wrong-shaped arrays become mypy errors, before anything runs

Documentation · Get started · Bug gallery · Limitations

CI Python 3.13+ NumPy 2.5+ MIT license

Twelve lines of plain NumPy in an editor. numty infers each shape and mypy reports a transposed weight matrix and a missing keepdims before the code runs.

That file imports nothing from numty and annotates nothing. numty worked out that reshape(64, -1) of (64, 28, 28) is (64, 784), carried it into the @, and saw that sum(axis=1) drops an axis the division needs.

The second bug is the dangerous kind. With 10 samples instead of 64, NumPy would broadcast (10, 10) / (10,) without complaint and return probabilities normalised along the wrong axis.

The same example as text
import numpy as np
images = np.zeros((64, 28, 28))
weights = np.zeros((10, 784))  # transposed: should be (784, 10)
bias = np.zeros(10)

flat = images.reshape(64, -1)
logits =
…
Enter fullscreen mode Exit fullscreen mode

Top comments (0)