資料內(nèi)容:
1 在 Python 3.10 以上版本中訪問對象的注解字典
Python 3.10 在標(biāo)準庫中加入了一個新函數(shù):inspect.get_annotations()。在 Python 3.10
以上的版本中,調(diào)用該函數(shù)就是訪問對象注解字典的最佳做法。該函數(shù)還可以“解析”字符
串形式的注解。
有 時 會 因 為 某 些 原 因 看 不 到 inspect.get_annotations() , 也 可 以 直 接 訪 問
__annotations__ 數(shù)據(jù)成員。這方面的最佳實踐在 Python 3.10 中也發(fā)生了變化:從 Python
3.10 開始,Python 函數(shù)、類和模塊的 o.__annotations__ 保證可用。如果確定是要查看這
三種對象,只要利用 o.__annotations__ 讀取對象的注釋字典即可。
不過其他類型的可調(diào)用對象可能就沒有定義__annotations__屬性,比如由functools.
partial() 創(chuàng)建的可調(diào)用對象。當(dāng)訪問某個未知對象的 “__annotations__“ 時,Python
3.10 以 上 版 本 的 最 佳 做 法 是 帶 三 個 參 數(shù) 去 調(diào) 用 getattr() , 比 如 getattr(o,
'__annotations__', None)。
Before Python 3.10, accessing __annotations__ on a class that defines no annotations but that has
a parent class with annotations would return the parent’s __annotations__. In Python 3.10 and
newer, the child class’s annotations will be an empty dict instead.
2 在 Python 3.9 及更早的版本中訪問對象的注解字典
在 Python 3.9 及之前的版本中,訪問對象的注解字典要比新版本中復(fù)雜得多。這個是 Python
低版本的一個設(shè)計缺陷,特別是訪問類的注解時。
要訪問其他對象——函數(shù)、可調(diào)用對象和模塊——的注釋字典,最佳做法與 3.10 版本相同,
假定不想調(diào)用 inspect.get_annotations():你應(yīng)該用三個參數(shù)調(diào)用 getattr() ,以
訪問對象的 __annotations__ 屬性。
不幸的是,對于類而言,這并不是最佳做法。因為 `__annotations__ 是類的可選屬性,
并且類可以從基類繼承屬性,訪問某個類的 __annotations__ 屬性可能會無意間返回 基
類的注解數(shù)據(jù)