可以從任何代碼對象(以及擴充子產品/内置項)調用:從exec,execfile,從子產品名稱空間(導入期間),從類定義内,從方法/類方法/staticmethod中,從修飾函數/方法,從嵌套函數中。。。-是以總的來說沒有“召喚功能”,而且很難用它做任何好事。在
堆棧幀及其代碼對象是您可以獲得并檢查屬性的最通用的。在
這個函數在很多情況下都可以找到調用函數:import sys, inspect
def get_calling_function():
"""finds the calling function in many decent cases."""
fr = sys._getframe(1) # inspect.stack()[1][0]
co = fr.f_code
for get in (
lambda:fr.f_globals[co.co_name],
lambda:getattr(fr.f_locals['self'], co.co_name),
lambda:getattr(fr.f_locals['cls'], co.co_name),
lambda:fr.f_back.f_locals[co.co_name], # nested
lambda:fr.f_back.f_locals['func'], # decorators
lambda:fr.f_back.f_locals['meth'],
lambda:fr.f_back.f_locals['f'],
):
try:
func = get()
except (KeyError, AttributeError):
pass
else:
if func.__code__ == co:
return func
raise AttributeError("func not found")
# Usage
def f():
def nested_func():
print get_calling_function()
print get_calling_function()
nested_func()
class Y:
def meth(self, a, b=10, c=11):
print get_calling_function()
class Z:
def methz(self):
print get_calling_function()
z = Z()
z.methz()
return z
@classmethod
def clsmeth(cls):
print get_calling_function()
@staticmethod
def staticmeth():
print get_calling_function()
f()
y = Y()
z = y.meth(7)
z.methz()
y.clsmeth()
##y.staticmeth() # would fail
它發現:
^{pr2}$