python的inspect模塊正如他們的命名一樣,是用于檢查運行模塊的一些基本信息,有了inspect模塊,我們可以做很多有意思的事情,下面主要想探究一下inspect模塊
inspect.getmembers
def getmembers(object, predicate=None):
"""Return all members of an object as (name, value) pairs sorted by name.
Optionally, only return members that satisfy a given predicate."""
results = []
# 使用dir(builtin)獲取所有的attr-key
for key in dir(object):
try:
value = getattr(object, key)
except AttributeError:
continue
# 如果有預測函數則進行預測
if not predicate or predicate(value):
results.append((key, value))
results.sort()
return results
getmembers方法的實現非常簡單,其內部的實現就是用內建函數dir實現的。
inspect.currentframe
currentframe內部實現是通過sys._getframe實現的。在使用currentframe的時候要注意防止循環引用。
def handle_stackframe_without_leak():
frame = inspect.currentframe()
try:
# do something with the frame
finally:
del frame
inspect的使用
1. 獲取調用函數的實例
# file: util.py
def get_caller():
import inspect
try:
frame = inspect.currentframe()
call_frame = frame.f_back.f_back
call_frame_name = call_frame.f_code.co_varnames[0]
call_frame_self = call_frame.f_locals.get(call_frame_name, None)
except:
call_frame_self = None
finally:
del frame
return call_frame_self