python输出文本和值_Python函数参数的打印名和值

我想生成一个debug_print(),它将输出调用者变量和值,稍后我将把它扩展到只部分打印列表和dict等等。本文只关注打印调用者变量和值的第一部分。在

这篇文章由以下部分组成:debug_print的当前版本

构建测试用例

测试用例的输出

我想要的输出和问题区域

相关问题列表

抱歉,这篇文章有点长,但我只想表明我已经做了一些研究,真的很想得到一些帮助来解决我的问题(如倒数第二节所列)。在

debug_print的当前版本import inspect

def debug_print(*args):

try: # find code_context

# First try to use currentframe() (maybe not available in all implementations)

frame = inspect.currentframe()

if frame:

# Found a frame, so get the info, and strip space from the code_context

code_context = inspect.getframeinfo(frame.f_back).code_context[0].strip()

else:

# No frame, so use stack one level above us, and strip space around

# the 4th element, code_context

code_context = inspect.stack()[1][4][0].strip()

finally:

# Deterministic free references to the frame, to be on the safe side

del frame

print('Code context : {}'.format(code_context))

print('Value of args: {}\n'.format(args))

构建测试用例

^{pr2}$

测试用例的输出Code context : debug_print(a, b, c, b+2)

Value of args: (0.2, 1.2, 1.2, 3.2)

Code context : debug_print([4.1, 4.2], [[4.00, 4.01], ["4.1.0", '4.1.1']])

Value of args: ([4.1, 4.2], [[4.0, 4.01], ['4.1.0', '4.1.1']])

Code context : debug_print((5.1, 5.2), {6.1: 6.2})

Value of args: ((5.1, 5.2), {6.1: 6.2})

Code context : debug_print(my_func, my_alias_func, my_alias_func())

Value of args: (, , 7)

Code context : debug_print(my_list[:2], my_list[3:])

Value of args: ([1, 2], [4, 5])

Code context : 'multi-line call', c)

Value of args: (0.2, 1.2, 'multi-line call', 1.2)

想要的输出和问题区域

我希望输出如下内容:a: 0.2; b: 1.2; c: 1.2; 3.2

: [4.1, 4.2]; : [[4.0, 4.01], ['4.1.0', '4.1.1']]

: (5.1, 5.2); : {6.1: 6.2}

func: my_func; func: my_alias_func -> my_func; my_func(): 7

my_list[:2]: [1, 2]; my_list[3:]: [4, 5]

不过,我确实从相关问题中看到,这可能是设置了一个有点高的标准。但我越靠近,就越好。在

理想情况下,我可以循环使用原始参数代码

作为键,但我也最满意的方法是从code_上下文中提取真正的参数代码,然后将这些代码与实际的参数相结合。

但是,我不能简单地分割,上的代码上下文,因为它也可能是列表、dict或元组的一部分。如果可以使用一些python解析器来分割代码上下文,那么这可能是另一种探索方法。但我想避免使用eval。在

到目前为止,我的搜索还没有找到任何地方,我可以在那里得到函数实际参数列表,其中包含代码和值。(已经看到了对f_globals或func_globals的引用,但它们列出了模块可用的所有内容,我找不到将它们重新连接到变量arguemnt列表的方法)。在

附带说明:我知道可以使用debug_print(**kwargs)上的变体,然后使用debug_print(a=a, b=b; c=c; sum=b+2)之类的语句,但在编写调试语句时最好避免这种重复。在

相关问题清单

过去也有类似的问题,但大多数问题都涉及固定的参数,或者只是显示名称,如果有的话,我想同时显示名称和值。或者是一个指南来解析代码上下文以匹配给定的参数。但下面是一些相关的问题:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值