python调用函数输入列表_获取python函数中使用/调用的函数的列表

更新:添加了Python2.7

测试并确认使用Python2.7、Python3.5和{}

dis输出)是我自己的:

设置:import dis

import sys

from contextlib import contextmanager

# setup test environment

def a(_,__):

pass

def b(_,__,___):

pass

def c(_):

pass

def g():

pass

d = 4

def test(flag):

e = c

if flag:

a(a(b,c), [l for l in g(1, x=2)])

else:

b(a, int(flag), c(e))

d = d + 1

def calculate(a, b, operator):

if operator == Operator.add:

add(a, b)

elif operator == Operator.subtract:

subtract(a, b)

class Operator(object):

add = "add"

subtract = "subtract"

Python 2/3兼容性:

^{pr2}$

代码:def get_function_calls(func, built_ins=False):

# the used instructions

ins = list(dis.get_instructions(func))[::-1]

# dict for function names (so they are unique)

names = {}

# go through call stack

for i, inst in list(enumerate(ins))[::-1]:

# find last CALL_FUNCTION

if inst.opname[:13] == "CALL_FUNCTION":

# function takes ins[i].arg number of arguments

ep = i + inst.arg + (2 if inst.opname[13:16] == "_KW" else 1)

# parse argument list (Python2)

if inst.arg == 257:

k = i+1

while k < len(ins) and ins[k].opname != "BUILD_LIST":

k += 1

ep = k-1

# LOAD that loaded this function

entry = ins[ep]

# ignore list comprehensions / ...

name = str(entry.argval)

if "." not in name and entry.opname == "LOAD_GLOBAL" and (built_ins or not hasattr(builtin, name)):

# save name of this function

names[name] = True

# reduce this CALL_FUNCTION and all its paramters to one entry

ins = ins[:i] + [entry] + ins[ep + 1:]

return sorted(list(names.keys()))

输出:> print(get_function_calls(test))

> ['a', 'b', 'c', 'g']

> print(get_function_calls(test, built_ins=True))

> ['a', 'b', 'c', 'g', 'int']

> print(get_function_calls(calculate))

> ['add', 'subtract']

由于Patrick Haugh关于^{}的评论已经超过2小时了,我认为这篇文章是免费的。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值