4

Python doesn't check types at compile time because it can't, at least in some circumstances. But has anyone come up with a mechanism to do compile-time type checking based on extra annotations by the user? Something like pylint which uses extra guarantees by the author? I'm thinking of something like:

#guarantee(argument=int, return_type=int)
def f(x):
    return x + 3

#guarantee(argument=int, return_type=str)
def g(x):
    return "%d times" % x

y = f(6)

# works, z = "9 times"
z = g(y)
# error
a = f(z)

This checker would interpret the comments above each function, realize that f(x) is only supposed to accept int but z comes from g(x) so it's a str. Is there any product which does something similar to this?

4

3 回答 3

2

PEP 3107最近完成了(最近是在去年的某个时间),它为变量和函数引入了注释。不幸的是(从 pep 的数量可以看出)这仅适用于 Python 3.x,因此您编写的任何检查器(甚至代码)都将仅适用于 Python 3(这确实不是一件坏事)。

您提到了 pylint,所以我假设您实际上并不希望在编译时运行检查,而是在编译后进行检查。这将是一个很棒的工具,可以在代码质量邮件列表中讨论。

于 2013-04-18T22:15:58.950 回答
1

我认为您缺少的关键字是decorator.

您可以编写自己的装饰器来执行以下操作:

@check(bar=int)
foo(bar):
    pass

您可以在此处查看示例实现。虽然这对于编译检查当然无效,因为它是在运行时完成的。

于 2013-04-18T22:08:48.353 回答
0

我不确定这是对 Python 中现有运行时机制的重大改进。例如,

def f(x):
    if not isinstance(x, int):
        raise TypeError("Expected integer")
    return x + 3

def g(x):
    return "%d times" % x

# Works.
y = f(6)
z = g(y)
# Fails, raises TypeError.
a = f(z)

换句话说,如果不对 Python 中每个对象的每个函数和每个方法进行注释,就很难静态地确定其中一个f或的返回类型是什么g。我怀疑任何沿着这些思路的静态检查器都会有任何价值。

即使您在函数中添加了返回类型描述符,这真的是一种保证吗?它看起来很像可能无法与代码一起更新的文档,从而导致以后由于不正确的假设而导致的更隐蔽的错误。

于 2013-04-18T21:56:17.133 回答