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