One - One Code All

Blog Content

Python3 函数注解

Python   2013-01-20 20:30:33

Python3提供一种语法,用于为函数声明中的参数和返回值附加元数据。下面的例子是注解后的版本,特点在第一行:

def clip(text : str, max_len : 'int > 0' = 80) -> str:
    """在max_len前面或后面的第一个空格处截断文本 
    """
    end = None
    if len(text) > max_len:
        space_before = text.rfind(' ', 0, max_len)
        if space_before >= 0
            end = space_before
        else:
            space_after = text.rfind(' ', max_len)       # 返回字符串最后一次出现的位置,没有则返回-1 
            if space_after >= 0:
                end = space_after
    if end is None:        # 没找到空格
        end = len(text)
    return text[:end].rstrip()        # 删除字符串末尾指定的字符串,默认为空格


1.函数声明中的各个参数可以在:后增加注解表达式。

2.如果参数由默认值,注解放在参数名和 = 号之间。

3.如果注解有返回值,在 ) 和函数末尾的:之间增加 -> 和一个表达式。那个表达式可以是任何类型。注解中最常用的类型是类(如 str 或 int)和字符串(如 'int > 0')。


注解不会做任何处理,只是存储在函数的__annotations__属性(一个字典)中:


>>> from clip_annot import clip

>>> clip._annotations__

{'text' : , 'max_len' : 'int > 0', 'return' : }

'return'键保存的是返回值注解,即函数声明里以 -> 标记的部分。


Python对注解所做的唯一的事情是,把他们存储在函数的__annotations__属性里。仅此而已,Python不做检查,不做强制,不做验证,什么操作都不做。换句话,注解对Python解释器没任何意义。注解只是元数据,可以供IDE、框架和装饰器等工具使用。



上一篇:Python两个列表里元素对应相乘,列表相除
下一篇:python列表排序list.sort(cmp=None, key=None, reverse=False)

The minute you think of giving up, think of the reason why you held on so long.