首页 > 解决方案 > 有没有办法像调用者所说的那样在被调用者中获取函数参数?

问题描述

我想实现调用foo(2*3)prints 2*3

原因是我尝试创建一个用于查询数据文件的测试框架,并且我想打印带有断言结果的查询语句。

我试图通过inspect模块让它工作,但我无法让它工作。

标签: pythoncode-inspection

解决方案


In general, the answer is "no", since the value received by the function is the result of the expression 2*3, not the expression itself. However, in Python almost anything is possible if you really want it ;-)

For simple cases you could achieve this using the inspect module like this:

#!/usr/bin/env python3

import inspect


def foo(x):
    context = inspect.stack()[1].code_context[0]
    print(context)


def main():
    foo(2 * 3)


if __name__ == '__main__':
    main()

This will print:

    foo(2 * 3)

It would be trivial to get the part 2 * 3 from this string using a regular expression. However, if the function call is not on a single line, or if the line contains multiple statements, this simple trick will not work properly. It might be possible with more advanced coding, but I guess your use case is to simply print the expression in a test report or something like that? If so, this solution might be just good enough.


推荐阅读