PoC: Generic-based Physical Type hints for Quantity#19149
PoC: Generic-based Physical Type hints for Quantity#19149AbhiLohar wants to merge 1 commit intoastropy:mainfrom
Conversation
|
Thank you for your contribution to Astropy! 🌌 This checklist is meant to remind the package maintainers who will review this pull request of some common things to look for.
|
|
@AbhiLohar, thanks for the PR. This does highlight one of the challenges of parametrizing by the dimension — we need a new dimension class for every possible dimension. E.g. |
|
For shape typing, see progress mentioned at https://blog.scientific-python.org/numpy/fellowship-program-2025-retrospective/#the-shape-typing-frontier-numtype - though looking at https://github.com/numpy/numtype/blob/main/src/_numtype/_shape.pyi, the shape-supporting part is still more like (numerical) dimensionality support -- I do not see how that, so far, could be easily used to support things like a shape ending in 3 or so. For us, in principle I guess it is possible to make physical type instances classes instead. I suspect, though, that this problem will go away, as surely there are other classes where equivalents of More relevantly, perhaps: what exactly does the current implementation catch? Say I have a function |
|
Hi @mhvk, I ran the test case you suggested. Currently, Mypy returns Success for f(10 * u.m) even when f expects Quantity[Time]. This confirms that the current PoC only enforces type safety when the user explicitly annotates the variable. The 'blind spot' is that unit multiplication doesn't yet know how to return a specific Quantity[D]. @nstarman, this really highlights why the 'mapping' or 'exponent tuple' approach you mentioned is the logical next step. To make this work for end-users, we would need to:
I'm going to look into how we might implement a trial @overload to see if we can bridge this gap! Thank you! |
This is a Proof of Concept (PoC) exploring the Generic approach for Quantity as discussed in #19034.
By inheriting from Generic[D], we allow static type checkers to see the physical dimension of a Quantity. Locally, this successfully catches unit mismatches that Annotated currently misses:
This implementation avoids using unit instances as types, addressing the concern that "units are not types".