打印变量名及其值的打印函数

Anu*_*ush 0 python

为了调试,我经常想打印一个变量。我这样做,例如:

打印(“cat_litter”,cat_litter)

那就是我打印变量名及其值。是否可以定义一个函数来为我执行此操作,以便我可以调用诸如“printwithname(cat_litter)”之类的东西。

Bre*_*257 5

不需要功能!Python 3.8+ f-strings 直接支持这种打印:

foo = 1
bar = 2
baz = "Something else"
print(f'{foo=}, {bar=}, {baz=}')
Run Code Online (Sandbox Code Playgroud)

https://docs.python.org/3/whatsnew/3.8.html#f-strings-support-for-self-documenting-expressions-and-debugging

Python 3.6 -> 3.7 解决方法:

Python:打印变量的名称和值?