The three answers¶
Every rule returns one of three objects. Together they are the type
Outcome.
| Answer | Fields | What it claims |
|---|---|---|
Known |
value |
NumPy succeeds and gives exactly this result, for every assignment of the names. |
Refused |
refusal |
NumPy raises, for every assignment of the names. |
Unknown |
reason, likely |
Nothing. The result depends on sizes the rule was not told. |
An assignment gives every name a non-negative integer. "For every assignment" includes the awkward ones: a name that is 0, a name that is 1, two names with the same value.
Known¶
Known.value is the result. For a shape rule it is a shape, for
broadcast_pair, match_pair and slice_length it is one size, and for the
element-type rules it is a name such as 'float32', a tuple of names, or a
bool.
The product of a (2, n) matrix and an (n, 5) matrix is (2, 5) whatever
n is, so the answer is Known although n is not.
Refused¶
Refused.refusal is a Refusal with three fields:
| Field | Holds |
|---|---|
kind |
A stable identifier of the check that failed, such as 'broadcast' or 'axis-out-of-range'. Branch on this. |
message |
The reason in words. str(refusal) gives the same text. |
raises |
The name of the exception NumPy raises: 'ValueError', 'IndexError', 'AxisError' or 'TypeError'. |
>>> answer = sr.reduce((4, 5), axis=2)
>>> answer.refusal.kind
'axis-out-of-range'
>>> answer.refusal.raises
'AxisError'
>>> print(answer.refusal)
axis 2 is out of bounds for an array of 2 dimensions
AxisError is numpy.exceptions.AxisError. It is a subclass of both
ValueError and IndexError.
The message is written by shaperules and is not NumPy's message. A client
that wants to show NumPy's own words makes the call and lets NumPy raise.
Every kind is listed in the refusals reference.
A refusal can be proven with names in the shapes. n + 2 and n + 3 are
never equal, and neither can be 1:
Unknown¶
Unknown means the rule could prove neither of the other two. reason says
what the answer depends on.
>>> answer = sr.matmul((2, "n"), ("m", 5))
>>> answer.reason
'the inner sizes of the product must be equal: n and m'
With every size a plain integer, the shape rules do not answer Unknown. The
tests assert this for each rule.
The likely reading¶
Unknown.likely is for a caller that wants a best reading all the same. It is
what holds once the doubt is set aside:
- the call is assumed to be valid;
- no name is assumed to be 0 or 1, or equal to another name.
likely is a Known, a Refused, or None when there is no single best
reading. It is not a proof. The three cases, on one axis of a broadcast:
>>> sr.broadcast(("n",), (3,)).likely
Known(value=(3,))
>>> sr.broadcast(("n",), ("m",)).likely is None
True
>>> sr.broadcast(("n",), ("n - 1",)).likely.refusal.kind
'broadcast'
In the first, the call is valid only when n is 3 or 1, and the result is
(3,) both times. In the second, the call is valid when the two are equal
or when one of them is 1, and the result is (n,) in some of those cases and
(m,) in others, so there is no one reading. In the third, the sizes are
never equal, and the call works only when n is 1 or 2. For any other n it
raises, so the likely reading is a refusal.
A likely reading is wrong for some assignments by construction. Slicing off
the first row gives n-1 rows unless there are no rows to begin with:
>>> answer = sr.index(("n", 4), slice(1, None))
>>> answer.reason
'the slice selects n-1 elements only when the axis, of size n, is long enough'
>>> sr.fmt_shape(answer.likely.value)
'(n-1, 4)'
At n = 0 NumPy gives (0, 4), and n-1 would be -1. So a client that must
match NumPy cannot act on likely. A type checker can, because (n-1, 4) is
what the author of a[1:] means.
Reading an answer in code¶
The three classes are frozen dataclasses. Tell them apart with isinstance
or with a match statement:
>>> def describe(answer):
... match answer:
... case sr.Known(value):
... return f"known: {sr.fmt_shape(value)}"
... case sr.Refused(refusal):
... return f"refused ({refusal.kind}): NumPy raises {refusal.raises}"
... case sr.Unknown(likely=sr.Known(value)):
... return f"unknown, likely {sr.fmt_shape(value)}"
... case sr.Unknown(reason=reason):
... return f"unknown: {reason}"
>>> describe(sr.matmul((2, "n"), ("n", 5)))
'known: (2, 5)'
>>> describe(sr.matmul((2, 3), (4, 5)))
'refused (matmul-core): NumPy raises ValueError'
>>> describe(sr.matmul((2, 1), ("n", 5)))
'unknown, likely (2, 5)'
>>> describe(sr.matmul((2, "n"), ("m", 5)))
'unknown: the inner sizes of the product must be equal: n and m'
Answers compare with ==, which is convenient in tests:
>>> sr.result_type("int8", "uint8") == sr.Known("int16")
True
>>> sr.broadcast(("n", 1), (3,)) == sr.Known(sr.shape("n", 3))
True
unwrap and best¶
Two methods cover the common ways of using an answer without matching on it.
unwrap is for a caller that accepts proofs only. It returns the value of a
Known and raises for the other two: ShapeRefused for a Refused,
ShapeUnknown for an Unknown. Both are subclasses of RuleError.
>>> sr.broadcast((3, 1), (4,)).unwrap()
(3, 4)
>>> sr.broadcast((3,), (4,)).unwrap()
Traceback (most recent call last):
...
shaperules.outcome.ShapeRefused: shapes (3,) (4,) do not broadcast: they disagree at axis -1
>>> sr.broadcast(("n",), ("m",)).unwrap()
Traceback (most recent call last):
...
shaperules.outcome.ShapeUnknown: sizes at axis -1 must be equal or 1: n and m
ShapeRefused carries the refusal and ShapeUnknown carries the reason:
>>> try:
... sr.broadcast((3,), (4,)).unwrap()
... except sr.ShapeRefused as error:
... print(error.refusal.kind, error.refusal.raises)
broadcast ValueError
best is for a caller that wants a value where there is one to be had. It
returns the value of a Known, the likely value of an Unknown whose likely
reading is a Known, and None otherwise.
>>> sr.broadcast((3, 1), (4,)).best()
(3, 4)
>>> sr.broadcast(("n",), (3,)).best()
(3,)
>>> sr.broadcast(("n",), ("m",)).best() is None
True
>>> sr.broadcast((3,), (4,)).best() is None
True
best returns None for a refusal and for a doubt with no likely value
alike. A caller that needs to tell those apart matches on the answer.
Answers and exceptions¶
A rule answers Refused when NumPy would raise for the shapes given. It
raises an exception itself when the question is malformed: a size that is
negative, a formula that does not parse, an axis that is not an integer, an
index item that is not part of basic indexing.
>>> sr.reduce((3,), axis=True)
Traceback (most recent call last):
...
TypeError: an axis is an integer, not bool
>>> sr.index((3,), "x")
Traceback (most recent call last):
...
TypeError: not a basic index: 'x'
>>> sr.index((3,), slice(None, None, 0))
Traceback (most recent call last):
...
ValueError: slice step cannot be zero
Which answers to act on is the subject of Writing a client. Why there are three answers and not two is in Design.