python - Python 3's "函数注释有什么用?

函数注释:PEP-3107

我遇到了一段演示 Python3 函数注释的代码片段。这个概念很简单,但我想不出为什么这些是在 Python3 中实现的,或者它们有什么好的用途。也许SO可以启发我?

它是如何工作的:

def foo(a: 'x', b: 5 + 6, c: list) -> max(2, 9):
    ... function body ...

参数后面冒号后面的都是一个“注解”,->后面的信息是函数返回值的注解。

foo.func_annotations 会返回一个字典:

{'a': 'x',
 'b': 11,
 'c': list,
 'return': 9}

提供这个有什么意义?

最佳答案

函数注释就是你对它们所做的。

它们可用于文档:

def kinetic_energy(mass: 'in kilograms', velocity: 'in meters per second'):
     ...

它们可用于前置条件检查:

def validate(func, locals):
    for var, test in func.__annotations__.items():
        value = locals[var]
        msg = 'Var: {0}\tValue: {1}\tTest: {2.__name__}'.format(var, value, test)
        assert test(value), msg


def is_int(x):
    return isinstance(x, int)

def between(lo, hi):
    def _between(x):
            return lo <= x <= hi
    return _between

def f(x: between(3, 10), y: is_int):
    validate(f, locals())
    print(x, y)


>>> f(0, 31.1)
Traceback (most recent call last):
   ... 
AssertionError: Var: y  Value: 31.1 Test: is_int

另见 http://www.python.org/dev/peps/pep-0362/一种实现类型检查的方法。

https://stackoverflow.com/questions/3038033/

相关文章:

linux - 如何反汇编原始 16 位 x86 机器代码?

linux - 重定向 curl 后获取最终 URL

python - 为什么 Python 的原始字符串文字不能以单个反斜杠结尾?

bash - 试图在 Bash 的变量中嵌入换行符

linux - 检查目录是否用 bash 挂载

python - 如何检查字符串中的特定字符?

regexp)": what d">python - 命名正则表达式组 "(?Pregexp)": what d

mysql - 复制整个 MySQL 数据库

linux - 亚马逊 Linux : "apt-get: command not found"

python - 值错误 : setting an array element with a seq