它可能無法正確地做這個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']
這實在是太醜陋和複雜的,但可能工作爲你所需要的。它通過查找調用該函數的行中使用的所有變量並將它們與當前函數進行比較來工作。
來源
2012-07-18 18:27:59
Tar
我懷疑這是可能的。你想要這樣做的任何特定原因? – mgilson 2012-07-18 17:34:46
通常當人們問如何做這樣的事情時,他們正在做一件非常糟糕的事情。你能澄清這將起什麼作用嗎? – cdhowie 2012-07-18 17:35:37
您可以更改零件的__name__,但我不明白爲什麼要這樣做。另外,看看裝飾文檔。 – sean 2012-07-18 17:35:40