如何编写函数检测目标函数中是否调用to_pandas()方法
判断函数是否调用了to_pandas()方法
你的问题出在字节码指令的判断上——普通函数调用用的是CALL_FUNCTION,但对象方法调用(比如colunas.to_pandas())对应的是LOAD_METHOD + CALL_METHOD的指令组合,你原来的代码只处理了前者,所以抓不到to_pandas()的调用。
下面是修正后的实现,能准确检测目标函数内部是否调用了to_pandas()方法:
import dis def has_to_pandas_call(fn): bytecode = dis.Bytecode(fn) loaded_method = None for instr in bytecode: # 加载对象方法时,记录方法名 if instr.opname == "LOAD_METHOD": loaded_method = instr.argval # 调用方法时,检查之前加载的是不是to_pandas elif instr.opname == "CALL_METHOD" and loaded_method == "to_pandas": return True return False
测试示例
用你提供的extract_and_transform函数测试:
def extract_and_transform(): colunas = ['nome', ' idade', ' cpf', ' ativo', ' nascimento', ' estado'] df = colunas.to_pandas() return True # 测试结果:返回True print(has_to_pandas_call(extract_and_transform)) # 测试一个没调用to_pandas的函数 def no_to_pandas(): return [1,2,3] # 测试结果:返回False print(has_to_pandas_call(no_to_pandas))
为什么你的原代码失效?
原代码只处理了CALL_FUNCTION指令,这是用来调用普通函数(比如print()、len())的。而调用对象的实例方法时,Python字节码会先执行LOAD_METHOD加载方法名,再用CALL_METHOD执行调用,所以必须针对这组指令做检测才能捕获方法调用行为。
内容的提问来源于stack exchange,提问作者Lucca Ribeiro
相关产品推荐
相关产品推荐

