typeshed icon indicating copy to clipboard operation
typeshed copied to clipboard

numbers module

Open Gouvernathor opened this issue 1 year ago • 2 comments

image The signature of Rational.__truediv__ is marked as the following: image First of, _ComplexLike sounds like it should be numbers.Complex. But second, the signature should be more refined :

  • the divisor cannot be just any value, it has to be a number, so at a minimum numbers.Complex instead of Unknown. The typing signature should be (self, Complex) -> Complex.
  • when passing a Real as a divisor, the result cannot have an imaginary part and must be Real too. I'd go as far as saying that a Rational divisor would yield a Rational dividend. In any case, a (self, Real) -> Real overload should be defined. And as a bonus, a (self, Rational) -> Rational one too.

Gouvernathor avatar May 05 '24 03:05 Gouvernathor

Please note that your IDE's understanding of the types is a poor representation of how the types are annotated in typeshed. Rational has no annotations for __truediv__ at the moment, instead the signature is inherited from Complex:

https://github.com/python/typeshed/blob/4005c2f2145ed7a9917f838547844e64fffd69a4/stdlib/numbers.pyi#L91-L92

other isn't annotated at all, at the moment. See also the note about _ComplexLike at the beginning of the file:

https://github.com/python/typeshed/blob/4005c2f2145ed7a9917f838547844e64fffd69a4/stdlib/numbers.pyi#L4-L8

We of course accept any improvements in this area (and everywhere else)!

srittau avatar May 05 '24 10:05 srittau

Well, my type checker (pyright) does consider float as a suclass of Real, so the way it works seems right to me considering the information that it's given. In any case, I can (eventually) submit a merge request with basically what I proposed but with you local types instead of the official numbers ones, and also applied to the other operations. But I'm not a typing virtuoso so it will need a second look.

But having thought a little about it, maybe an implementation of Rational that would return a complex from the division of two rationals may fit in the python bounds of the numbers interface. Hell, it may even make some mathematical sense for all I know. What I was talking about is the behavior of float, int, Decimal and Fractions but it may be a limitation on Rational at-large. I'll be asking about it on the Python Discourse.

Gouvernathor avatar May 05 '24 12:05 Gouvernathor