python - 有没有办法像调用者所说的那样在被调用者中获取函数参数?
问题描述
我想实现调用foo(2*3)
prints 2*3
。
原因是我尝试创建一个用于查询数据文件的测试框架,并且我想打印带有断言结果的查询语句。
我试图通过inspect
模块让它工作,但我无法让它工作。
解决方案
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.
推荐阅读
- python - Python 包管理器 **pip** 是否有类似 yarn 链接的东西?
- vb.net - 在传递值之前等待线程完成
- mysql - Combine multiple sql update statements into one statement
- javascript - 添加描边并更改数据圈中文字的文字颜色
- git - 在 Azure DevOps Server 2019 上,如何在不应用其策略的情况下将主分支合并到开发分支?
- facebook - 将此分享添加到 Facebook 应用而不是 m.facebook.com
- c# - 如何修复 CSOM 错误:位置 X 的数据类型与预期的不同?
- webpack - 为什么我的 Webpack-cleanup-plugin 会删除我的排除文件?
- reactjs - 反应:按钮不起作用/无法执行状态更新
- python - Python——函数装饰器导致函数被调用两次