graphix icon indicating copy to clipboard operation
graphix copied to clipboard

Resolve union types of `float` / `complex` and symbolic stuff

Open EarlMilktea opened this issue 11 months ago • 1 comments

Describe the feature you'd like

Refactor simulators or/and update annotations to accurately keep track of types and get rid of unions such as npt.NDArray[np.complex128 | np.object_].

Additional context

Union types in return type annotations are in general not good, as users/developers need to further narrow types frequently.

EarlMilktea avatar Apr 16 '25 03:04 EarlMilktea

@thierry-martinez

I have a few questions and suggestions:

  • API design of Expression

Why not change them to always return Expression by removing automatic coercion of Expression to numbers? This will remove union return types and lead to type stability.

@abstractmethod
# def __mul__(self, other: object) -> ExpressionOrFloat:
def __mul__(self, other: object) -> Expression:
  • API design of substitutions

Why not remove | complex type unions and make them closed mappings on Expression ? Sadly Python type system is not strong enough to express the nature of variable substitutions, namely

  • return type is float if all the parameters are substituted
  • Expression otherwise

This kind of value-dependent type branch is generally incompatible with static typing (or even impossible in some compiled languages) and then I would like to simplify.

MEMO: All the above suggestions are basically optional for public APIs as current annotations are natural for us humans, but for the internals (ex. function calls inside simulators), it is very critical to remove value-dependent type branches. We may add constrained versions of the current APIs for internal use.

EarlMilktea avatar Apr 16 '25 11:04 EarlMilktea