【问题标题】:Scalar type checking does not work in python标量类型检查在 python 中不起作用
【发布时间】:2021-08-29 12:37:56
【问题描述】:

标量类型检查在 Python (v 3.8.6) 中不起作用。

def test(x: int) -> int:
    print(type(x))
    return x

a = test('a')

没有 int 作为输入参数完全没有关系。它也不表示 int 不是输出参数。

输出:

<class 'str'>

我希望有 ValueError!

【问题讨论】:

标签: python typing strict


【解决方案1】:

你说的是函数注释

def test(x: int) -&gt; int.

这意味着该函数应采用 int 参数,并且还应具有 int 返回值。这些是可选的,不是由 Python 强制执行的,但它们对静态类型分析工具很有用,并帮助 IDE 完成代码和重构。

在此处阅读更多信息:https://docs.python.org/3/glossary.html#term-function-annotation

【讨论】:

    猜你喜欢
    • 2018-07-23
    • 2018-11-21
    • 2013-12-22
    • 1970-01-01
    • 1970-01-01
    • 2020-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多