inspect — 检测 Python 物件內容
用 inspect 檢查物件的形态
>>> import inspect
>>> inspect.ismodule(inspect) # 檢查 inspect 是否為模組
True
>>> inspect.ismethod(inspect) # 檢查 inspect 是否為物件方法
False
>>> inspect.isfunction(len) # 檢查 len 是否為函式
True
>>> inspect.isbuiltin(len) # 檢查 len 是否為內建函式
True
>>> inspect.isawaitable(inspect) # 檢查 inspect 是否可用於 await expression
False
>>>
透過 inspect 取得物件內的資訊,例如說物件的 docstring、comment 甚至是 source code:
>>> inspect.getdoc(len) # 取得 len 的 docstring
'Return the number of items in a container.'
>>> inspect.getsource(inspect) # 取得 inspect 的 source code
'"""Get useful information from live Python objects.\n\n
This module encapsulates the interface provided by the
internal special\nattributes (co_*, im_*, tb_*, etc.) in ...'
>>>
透過 inspect.getmembers,我們可以取得一個物件裏面所有的 member:
>>> inspect.getmembers(len)
[('__call__',
),
('__class__', ),
('__delattr__',
...,
('__setattr__',
),
('__sizeof__',
),
('__str__',
),
('__subclasshook__',
),
('__text_signature__', '($module, obj, /)')]
>>> import tabnanny
>>> inspect.getmembers(tabnanny, inspect.isfunction) # get only function
[('check', ),
('errprint', ),
('format_witnesses', ),
('main', ),
('process_tokens', )]
inspect.signature,可以獲得 callable 的 Signature 物件
>>> def foo(name, a: int, b: float):
... pass
...
>>> sig = inspect.signature(foo)
>>> sig
>>> str(sig)
'(name, a:int, b:float)'
>>> sig.parameters
mappingproxy(OrderedDict([('name', ), ('a', ), ('b', )]))
透過 Signature.bind,我們可以把參數給綁定到 signature 上:
>>> args = ('foobar', 10)
>>> kwargs = {'b': 23.4}
>>> bound = sig.bind(*args, **kwargs) # bind args to signature parameters
>>> bound
>>> bound.arguments['name']
'foobar'
>>> bound.arguments['a']
10
>>> bound.arguments['b']
23.4