如何打字实数,并将其与INT进行比较
我有一个输入实数的函数。实际上,它可能是 int
或 float
。我希望它检查它是否为 >0
例如
def f(x):
return x > 0
现在我希望对该函数进行类型检查。由于我希望 x
是任何实数,所以我自然地写道:
from numbers import Real
def f(x: Real) -> bool:
return x > 0
但是问题,根据 Pyright:
Operator ">" not supported for types "Real" and "Literal[0]"
Operator ">" not supported for types "Real" and "Literal[0]"
[Pyright: reportGeneralTypeIssues]
这是我的两个问题:
- 为什么
Real
和之间的比较>int
未定义?这是一个与抽象基类相关的问题吗? - 我应该使用什么类型?我别无选择,只能使用 Union[int, float](我觉得有点难看)?
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
andint
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)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论