2019年7月18日 星期四

教學

https://sites.google.com/site/zsgititit/home/python-cheng-shi-she-ji/python-bian-shu-yu-yun-suan-zi

inspect – 探測 Python 物件內容

inspect – 探測 Python 物件內容

The inspect module provides several useful functions to help get information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects. For example, it can help you examine the contents of a class, retrieve the source code of a method, extract and format the argument list for a function, or get all the information you need to display a detailed traceback.
Source code: Lib/inspect.py
在 Python 界,人人都能朗朗上口的一句話大概就是「Python 裏什麼東西都是物件」,既然如此,有沒有辦法在 runtime 得到這些資訊呢?答案是可以的,透過 inspect 函式庫,我們可以探測幾乎任何的東西 (凡舉模組、類別、函式、traceback、frame 甚至是 code 的資訊!)。inspect 主要提供四大功能:型態檢查、獲取程式碼、探測類別與函式、檢查直譯器堆疊。

01. Quickstart Tutorial

首先我們來使用 inspect 檢查物件的型態!
我們也可以透過 inspect 取得物件內的資訊,例如說物件的 docstring、comment 甚至是 source code:
透過 inspect.getmembers,我們可以取得一個物件裏面所有的 member:
不過最有趣以及有用的,還是這個 inspect.signature,可以獲得 callable 的 Signature 物件:
透過 Signature.bind,我們可以把參數給綁定到 signature 上:

02. HOW-TO Guides

透過 signature.bind 以及 annotation 來做型態檢查

前面提到的 signature.bind 看似無用,但是卻可以用在型態檢查上面。在 PEP 484 中,提到了如何在 Python 裏面使用型態提示:
上面的 gcd 函式中,我們為參數 a 以及參數 b 加上型態提示為 int,而函式回傳值的型態提示為 int。只是這個很廢只有提示功能,我們可以嘗試丟入 float 數值看看:
Python 會很開心的忽略 annotation,回傳一個神奇的 float 數值給你。
要解決這個問題,我們可以手動的使用 assert 來檢查型態:
但是這根本沒有發揮 type hint 的效果啊!
額外加上一個 wrapper 來解決這個問題:
如此一來就能活用 inspect 來達到使用 annotation 檢查型態的功能了!

03. Discussions

暫時沒有。