如何打字实数,并将其与INT进行比较

发布于 2025-01-19 12:29:29 字数 818 浏览 2 评论 0原文

我有一个输入实数的函数。实际上,它可能是 intfloat。我希望它检查它是否为 >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 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)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文