Python3提供一種語法,用於為函數聲明中的參數和返回值附加元數據。下面的例子是注解后的版本,特點在第一行:
1 def clip(text : str, max_len : 'int > 0' = 80) -> str: 2 """在max_len前面或后面的第一個空格處截斷文本 3 """ 4 end = None 5 if len(text) > max_len: 6 space_before = text.rfind(' ', 0, max_len) 7 if space_before >= 0 8 end = space_before 9 else: 10 space_after = text.rfind(' ', max_len) # 返回字符串最后一次出現的位置,沒有則返回-1 11 if space_after >= 0: 12 end = space_after 13 if end is None: # 沒找到空格 14 end = len(text) 15 return text[:end].rstrip() # 刪除字符串末尾指定的字符串,默認為空格
1.函數聲明中的各個參數可以在:后增加注解表達式。
2.如果參數由默認值,注解放在參數名和 = 號之間。
3.如果注解有返回值,在 ) 和函數末尾的:之間增加 -> 和一個表達式。那個表達式可以是任何類型。注解中最常用的類型是類(如 str 或 int)和字符串(如 'int > 0')。
注解不會做任何處理,只是存儲在函數的__annotations__屬性(一個字典)中:
>>> from clip_annot import clip >>> clip._annotations__ {'text' : <class 'str'>, 'max_len' : 'int > 0', 'return' : <class 'str'>}
'return'鍵保存的是返回值注解,即函數聲明里以 -> 標記的部分。
Python對注解所做的唯一的事情是,把他們存儲在函數的__annotations__屬性里。僅此而已,Python不做檢查,不做強制,不做驗證,什么操作都不做。換句話,注解對Python解釋器沒任何意義。注解只是元數據,可以供IDE、框架和裝飾器等工具使用。