typeshed icon indicating copy to clipboard operation
typeshed copied to clipboard

Use abstract types from `numbers`

Open sobolevn opened this issue 3 years ago • 3 comments

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 be Real, 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:

  1. Use a base class in builtins.pyi
  2. Use Real.register(float) in builtins.pyi
  3. Use Real.register(float) in numbers.pyi (as runtime does)

sobolevn avatar Feb 15 '22 05:02 sobolevn

I don't think we can really do anything in typeshed. This is best handled on the type checker level.

srittau avatar Feb 15 '22 07:02 srittau

An approach like https://github.com/python/mypy/issues/3186#issuecomment-762121456 could be feasible.

hauntsaninja avatar Feb 15 '22 07:02 hauntsaninja

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.

srittau avatar Feb 15 '22 08:02 srittau

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

AlexWaygood avatar Nov 01 '23 18:11 AlexWaygood