typeshed
typeshed copied to clipboard
Use abstract types from `numbers`
Right now types declared in numbers.pyi
are not used.
This causes this problem:
from numbers import Real
def test(f: Real) -> Real:
return f
test(1.32)
# error: Argument 1 to "test" has incompatible type "float"; expected "Real"
But, in runtime:
-
float
is registered to beReal
, source: https://github.com/python/cpython/blob/12360aa159c42c7798fd14225d271e6fd84db7eb/Lib/numbers.py#L264 Also: -
complex
: https://github.com/python/cpython/blob/12360aa159c42c7798fd14225d271e6fd84db7eb/Lib/numbers.py#L144 -
int
: https://github.com/python/cpython/blob/12360aa159c42c7798fd14225d271e6fd84db7eb/Lib/numbers.py#L393
But, how can we type it? Options:
- Use a base class in
builtins.pyi
- Use
Real.register(float)
inbuiltins.pyi
- Use
Real.register(float)
innumbers.pyi
(as runtime does)
I don't think we can really do anything in typeshed. This is best handled on the type checker level.
An approach like https://github.com/python/mypy/issues/3186#issuecomment-762121456 could be feasible.
A typing feature that allows stubs to register a type with another type, similar to what abcs provide at runtime, would be useful for those legacy features, though.
I invested some energy a while back into seeing if you could do this, and I think the honest answer is that there's no way to make it work at typeshed. Mypy now gives a much more helpful error message if you try to use an abstract type from numbers
these days, following https://github.com/python/mypy/pull/15137.
Closing as per the rationale in https://github.com/python/mypy/issues/3186#issuecomment-1571512649