在显示调用函数的参数和值的实用函数中,我需要知道从另一个模块导入的可能的别名函数的原始名称。这可能适用于导入时使用别名的简单情况吗?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]()'使用对列表中函数对象的引用。 –