1

I have a function that inputs a real number. In practice it might be an int or a float. and I want it to check if it is >0

For example

def f(x):
   return x > 0

Now I want that function to be type checked. Since I wanted x to be any real number, I naturally wrote:

from numbers import Real

def f(x: Real) -> bool:
   return x > 0

But problem, according to pyright:

Operator ">" not supported for types "Real" and "Literal[0]"
  Operator ">" not supported for types "Real" and "Literal[0]"
[Pyright: reportGeneralTypeIssues]

Here come my two questions:

  • Why is the comparison between Real and int not defined? Is it an abstract-base-classes-related problem?
  • What type should I use instead? Do I have no choice but to use Union[int, float] (which I find a bit ugly)?
tbrugere
  • 755
  • 7
  • 17
  • The reason why I find the `Union[int, float]` ugly, is that for example, if someone creates a `Rational` class, and subclass `Real`, then my function should work on their type too – tbrugere Apr 07 '22 at 01:01
  • Why not just have `x: float` as the common least restrictive type? I don't have any complaints when I use integer as an input. – NotAName Apr 07 '22 at 01:12
  • You’re right it would work, this is actually a special case https://stackoverflow.com/questions/62725822/why-does-a-type-hint-float-accept-int-while-it-is-not-even-a-subclass I was a bit confused about it (in particular because when I tried that, my `assert isinstance(x, float)` fired exceptions) – tbrugere Apr 07 '22 at 01:37
  • It wouldn’t help with the subclassing problem (with the `Rational`), though that may be trying to overgeneralize – tbrugere Apr 07 '22 at 01:38
  • 1
    So, the state of affairs with regards to how `numbers` interacts with static type checkers is... well, you should just [read this answer to a related question](https://stackoverflow.com/a/69383462/5014455) – juanpa.arrivillaga Apr 07 '22 at 01:53
  • 1
    @juanpa.arrivillaga Thanks for the link, that makes it so much clearer. This problem looks like a tangled mess though. – tbrugere Apr 07 '22 at 02:01
  • 1
    I guess this is what happens when you try to statically typecheck a language that was designed for dynamic typing with duck-typing in mind. – tbrugere Apr 07 '22 at 02:03
  • @Nephanth yes, python had fully embraced a dynamic nature with virtual subclassing, but special-cases could be made, as pointed out in that answer, but really I think the problem was that numeric types were never coherently brought together in a type hierarchy, and too many projects developed out before the half-hearted attempt was made with the `numbers` module. – juanpa.arrivillaga Apr 07 '22 at 03:30

0 Answers0