gpt4 book ai didi

python - Python 中函数的别名

转载 作者:行者123 更新时间:2023-12-01 05:58:18 27 4
gpt4 key购买 nike

我想找到调用该函数的名称...即调用该函数的变量的名称。使用基本配方,即使用 __name__func_name 或检查基本堆栈对我来说不起作用。例如

def somefunc():
print "My name is: %s" % inspect.stack()[1][3]

a = somefunc
a()
# would output: out: "My name is: somefunc"
# whereas I want it to output: "My name is: a"

我的直觉告诉我我可以做到这一点,但我无法弄清楚。有Python大师吗?

最佳答案

可能不可能 100% 正确地完成此操作,但您可以尝试以下操作:

import inspect
import parser

# this flatten function is by mike c fletcher
def flatten(l, ltypes=(list, tuple)):
ltype = type(l)
l = list(l)
i = 0
while i < len(l):
while isinstance(l[i], ltypes):
if not l[i]:
l.pop(i)
i -= 1
break
else:
l[i:i + 1] = l[i]
i += 1
return ltype(l)

# function we're interested in
def a():
current_func = eval(inspect.stack()[0][3])
last_frame = inspect.stack()[1]
calling_code = last_frame[4][0]
syntax_tree = parser.expr(calling_code)
syntax_tree_tuple = parser.st2tuple(syntax_tree)
flat_syntax_tree_tuple = flatten(syntax_tree_tuple)
list_of_strings = filter(lambda s: type(s)==str,flat_syntax_tree_tuple)
list_of_valid_strings = []
for string in list_of_strings:
try:
st = parser.expr(string)
list_of_valid_strings.append(string)
except:
pass
list_of_candidates = filter(lambda s: eval(s)==current_func, list_of_valid_strings)
print list_of_candidates

# other function
def c():
pass

a()
b=a
a(),b(),c()
a(),c()
c(),b()

这将打印:

['a']
['a', 'b']
['a', 'b']
['a']
['b']

它相当丑陋且复杂,但可能适合您的需要。它的工作原理是查找调用该函数的行中使用的所有变量并将它们与当前函数进行比较。

关于python - Python 中函数的别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11547095/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com