函数注解
用于为函数声明中的参数和返回值附加元数据
一个有注解的clip函数:
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)
if space_after >= 0:
end = space_after
if end is None:
end = len(text)
return text[:end].rstrip()
输出:
# {'text': <class 'str'>, 'max_len': 'int > 0', 'return': <class 'str'>}
print(clip.__annotations__)