在顯示調用函數的參數和值的實用函數中,我需要知道從另一個模塊導入的可能的別名函數的原始名稱。這可能適用於導入時使用別名的簡單情況嗎?Unalias在Python中導入的函數?
下面是一個簡化的用例,其中,I首先從utilities.py
模塊呈現一些代碼:
import inspect
DEBUG_FLAG = True
def _log_args(*args):
"""Uses reflection to returning passing argument code with values."""
prev_frame = inspect.currentframe().f_back
func_name = prev_frame.f_code.co_name
code_context = inspect.getframeinfo(prev_frame.f_back).code_context[0].strip()
# Do some magic, which does work _unless_ func_name is aliased :-)
print('code context: {}'.format(code_context))
print('func_name : {}'.format(func_name))
return ', '.join(str(arg) for arg in args)
def format_args(*args):
"""Returns string with name of arguments with values."""
return _log_args(args)
def debug_print(*args):
"""Prints name of arguments with values."""
if DEBUG_FLAG:
print _log_args(args)
這裏是一些代碼訪問這些功能首先通過原始名稱,然後通過別名:
from utilities import debug_print, format_args, debug_print as debug, format_args as fargs
def main():
a, b = "text", (12, 13)
print "== Unaliased =="
test_text = format_args(a, b)
print test_text # Returns
debug_print(a, b)
print "\n== Aliased =="
test_text = fargs(a, b)
print test_text
debug(a, b)
if __name__ == '__main__':
main()
從這個輸出是:
== Unaliased ==
code context: test_text = format_args(a, b)
func_name : format_args
('text', (12, 13))
code context: debug_print(a, b)
func_name : debug_print
('text', (12, 13))
== Aliased ==
code context: test_text = fargs(a, b)
func_name : format_args
('text', (12, 13))
code context: debug(a, b)
func_name : debug_print
('text', (12, 13))
如可被發現我已經找到了正確的代碼上下文,並且我找到了調用函數的名字,但是第一次報告的是別名,而後者報告了實際的名稱。所以我的問題是是否可以反轉操作,以便我可以知道format_args
已被別名爲fargs
,並且debug_print
已被別名爲debug
?
一些相關的問題,這些問題做不地址這種逆轉走樣:
- Aliased name of a Function in Python
- Find name of dynamic method in Python
- Get __name__ of calling function's module in Python
- Print name and value of Python function arguments
簡而言之:沒有,沒有,沒有廣泛的AST解析和調用幀的源代碼分析,所以你可以猜測用什麼名字來產生調用。 –
@MartijnPieters,AST?那是抽象語法樹嗎? – holroy
是的,您必須加載源代碼,然後分析調用的方式以及可調用對象的名稱。請注意,您可以創建其他不一定具有名稱的引用; 'callables = [fargs,debug],然後'callables [0]()'使用對列表中函數對象的引用。 –