Skip to main content

shaperules

CI PyPI Python 3.11+ MIT licence

NumPy's shape and dtype rules as a pure-Python library with no dependencies. Give a rule the shapes of the operands and it answers with the shape of the result, without NumPy installed and without running anything.

A size is an integer, a formula over names such as n or 2*n+1, or unknown. Every rule answers one of three things:

  • Known(value): the result, proven for every value the names can take.
  • Refused(refusal): NumPy raises, for every value the names can take.
  • Unknown(reason, likely): it depends on sizes the rule was not told. likely is a best reading for a caller that wants one, and is not a proof.
>>> import shaperules as sr

>>> sr.broadcast((8, 1, 3), (5, 3))
Known(value=(8, 5, 3))

>>> product = sr.matmul(("batch", "n", 64), (64, 10))
>>> sr.fmt_shape(product.value)
'(batch, n, 10)'

>>> refused = sr.matmul((2, 3), (4, 5))
>>> refused.refusal.kind, refused.refusal.raises
('matmul-core', 'ValueError')

>>> doubt = sr.broadcast(("n",), (3,))
>>> doubt.reason
'sizes at axis -1 must be equal or 1: n and 3'
>>> doubt.likely
Known(value=(3,))

The last call is valid when n is 3 or 1 and raises in NumPy otherwise, so nothing is proven. A caller that must agree with NumPy exactly acts on Known and Refused and asks NumPy for the rest. A caller such as a type checker can carry on with likely.

Element types (dtypes) work the same way:

>>> sr.result_type("int8", "uint8").value
'int16'
>>> sr.result_type("float32", float).value
'float32'
>>> sr.ufunc_dtype("true_divide", "int32", "int32").value
'float64'
>>> sr.ufunc_dtype("subtract", "bool", "bool").refusal.raises
'TypeError'

Documentation: sofeikov.github.io/shaperules

Install

pip install shaperules
uv add shaperules

It needs Python 3.11 or later and installs nothing else.

What is covered

These rules are covered. Each one takes shapes or element types and answers with a shape, a size or an element type.

Area Rules NumPy calls they stand for
Broadcasting broadcast, broadcast_pair, match_pair np.broadcast_shapes, and so the shape of any element-wise operation
Matrix product matmul a @ b, np.matmul
Reductions reduce, reduce_shape, arg_reduce, cumulative np.sum, np.prod, np.any, np.max, np.min, np.argmax, np.cumsum and the like. reduce_shape takes the reduction's name and knows what each of 25 of them refuses
Reordering axes transpose, swapaxes, moveaxis a.T, np.transpose, np.swapaxes, np.moveaxis
Adding and removing axes squeeze, expand_dims np.squeeze, np.expand_dims
Regrouping elements reshape (with -1), concatenate, stack np.reshape, np.concatenate, np.stack
Basic indexing index, slice_length a[key] where the key holds integers, slices, None and ...
Element types result_type, can_cast, ufunc_dtype, ufunc_dtypes, reduce_dtype np.result_type, np.can_cast, the result type of every element-wise ufunc of one or two inputs, and of sixteen reductions

Fourteen element types are covered: bool, int8 to int64, uint8 to uint64, float16 to float64, complex64 and complex128. A Python int, float or complex among the operands is promoted the way NumPy 2 promotes a Python number (NEP 50).

Each rule is described with examples in the guide to the shape rules and the guide to element types.

How it is checked

NumPy is not needed to use shaperules. It is used by the tests, where it is the reference every answer is held against.

  • Shape rules. Hypothesis draws shapes whose sizes are formulas over a few names. The test asks the rule, then makes the real NumPy call for every assignment of the sizes 0 to 3 to those names. A Known answer must be NumPy's shape every time. A Refused answer must be an exception of the named class every time.
  • Element types. Promotion is compared with np.result_type for every single operand, every pair, every triple of different operands, and every combination of four array types. Every cell of every ufunc table and every reduction is compared with the NumPy call it stands for.
  • The tables. What a ufunc returns for each pair of element types is read from tables generated from NumPy by tools/generate_tables.py. A test generates them again on the NumPy under test and fails on any difference.
  • Versions. CI runs the suite on NumPy 2.1, the oldest version modelled, and on the latest, and installs the wheel into an environment with no NumPy to check that it answers there.
  • The examples. Every example in this README and in the documentation is run by the test suite.

The full account is in Checked against NumPy.

Status and limits

The following are not modelled:

  • A Python integer that does not fit the array's type. np.uint8(1) + 300 raises OverflowError in NumPy. That depends on a value, and shaperules sees types only.
  • Shapes of unknown rank. A shape is a tuple with one size per axis, so the number of axes is always known.
  • Indexing by arrays or boolean masks.
  • einsum, numpy.linalg, numpy.fft and the functions that build arrays.
  • Sums of products in the formula algebra. n*m + 1 has no form there and is read as an unknown size.
  • Element types outside the fourteen, such as datetime64, longdouble and object. A rule given one answers Unknown.

A refusal's message is written by shaperules and is not NumPy's message. The list with details is in Limitations and roadmap.

Where it comes from

The rules were extracted from numty, a mypy plugin that checks NumPy shapes statically, so that clients other than a type checker can use them. numty imports its size algebra and its dtype promotion from shaperules. A second intended client is the lazy layer of hotkernels, which needs the shape and element type of a NumPy call at run time without computing it. hotkernels does not use shaperules yet.

Documentation

Licence

MIT. See LICENSE.

Metadata

Release files for shaperules 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for shaperules 0.2.0
File Size Uploaded Provenance Actions
shaperules-0.2.0.tar.gz 182.4 kB With provenance Details for shaperules-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for shaperules 0.2.0
File Interpreter ABI Platform Actions
shaperules-0.2.0-py3-none-any.whl Python 3 none any Details for shaperules-0.2.0-py3-none-any.whl

Total release size: 222.4 kB

Release files / shaperules-0.2.0.tar.gz

Download URL shaperules-0.2.0.tar.gz
Size 182.4 kB
Tags Source
SHA-256 checksum
How to use checksums
3006a24bcf47fb5d9769966ac41a4ef0f3d0f5d7b7cf6562e75fc21c98bfe2de
BLAKE2b-256 checksum
How to use checksums
434263af30f0a1dc050a41fdc1733eeb88becc72c2bc2e80c0909a3dab5bbfa5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.

Transparency log

Release files / shaperules-0.2.0-py3-none-any.whl

Download URL shaperules-0.2.0-py3-none-any.whl
Size 40.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
3d794ba142131d14029faa7557ae85b94ad024a79baffa66e99ef3d1b3dc6b6a
BLAKE2b-256 checksum
How to use checksums
3e3c179af866b0649f78e172c28aa79b35ff98dbe6ab7011a51f74b95d426b4f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.

Transparency log

Security for shaperules 0.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for shaperules-0.2.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page