Closed charlesyuan314 closed 3 months ago
Very cool. What's the minimum required python version with this feature?
Very cool. What's the minimum required python version with this feature?
Python 3.8+. TypeIs
will be native in Python 3.13 and is backported by the typing_extensions
package.
actually can you figure out the minimum version of typing_extensions
required and add it to dev_tools/requirements/deps/runtime.txt
with a >=
constraint. We transitively depend on it already from a variety of other packages and the current pinned version for the CI is sufficient but whatever version I've got locally isn't new enough, and if you pip install qualtran
it will respect the runtime.txt
loosey-goosey specs rather than the pinned versions.
This change adds
TypeIs
to the signature ofis_symbolic
, thereby making spurious static type checker errors less likely and enabling us to remove uses ofcast
andassert
.Motivation
A common pattern in the codebase is as follows:
Unfortunately, this pattern doesn't play well with static type checkers such as mypy, which we use. As an example we actually encountered, consider this snippet from #1089 (just prior to commit 23577b27fb54f8bc5d88da05521fa092c6843a04):
Given the above code, mypy fails with the error:
This overly conservative type checking error occurs because in general, a static type checker cannot infer that the type of the argument of
is_symbolic
should be narrowed toint
fromUnion[int, Expr]
whenis_symbolic
returns False. Such inference is normally reserved for specific language patterns, such asisinstance
:We do sometimes use
isinstance
in the codebase for this purpose, but it is less general and we would prefer not to replaceis_symbolic
with it.Solution
Fortunately, we can do better and get the benefit of type narrowing using the recently introduced
TypeIs
type annotation. In brief, by annotating the return type ofis_symbolic
asTypeIs[sympy.Expr]
rather thanbool
, the static type checker will infer that whenis_symbolic(arg: Union[int, Expr])
returns True, thenarg: Expr
, and otherwisearg: int
.This PR makes the above change. Consequently, it safely removes numerous instances of
cast(int, ...)
,assert [not] isinstance(...)
,int(...)
, and similar patterns from the code.There are some caveats due to limitations of the Python type system:
is_symbolic
. To get the benefit, it is necessary to rewriteis_symbolic(x, y)
asis_symbolic(x) or is_symbolic(y)
.is_symbolic(self)
method defined on a class rather thansymbolics.types.is_symbolic
.HasLength
andShaped
. However, in one scenario, it was necessary to explicitly annotatek: SymbolicFloat
so that the type checker would inferk: Expr
rather thank: Union[HasLength, Shaped, Expr]
whenis_symbolic(k)
returns True.Tuple[SymbolicInt, ...]
toTuple[int, ...]
.