在Python中打印函数参数名称和值 [英] Print function parameter names and values in Python
问题描述
当调用一个函数时,我想打印其参数的名称和值.像这样:
When a function is called, I would like to print the names and values of it's parameters. Something like:
>>> def foo(bar, baz):
>>> magic_parameter_printing()
bar=0, baz=None
现在我使用格式:
print("bar={},baz={}".format(bar,baz))
但这是增加新参数的痛苦,并且总是存在丢失某些东西的风险.
But this is a pain as new parameters get added, and there's always the risk of missing something.
我找到了此答案,该答案在以下情况下适用于单个变量您知道它们是什么(并使用 eval
),但是我真的很希望能够对传递函数的所有参数执行此操作.
I found this answer which can work for single variables when you know what they are (and uses eval
), but I'd really like to be able to do it for all parameters a function is passed.
推荐答案
After you've add explanation how you want to apply this, I think best way will be to use decorator. It's more universal solution, because you can add it to any function in your code and it will print all debug info if debug mode is on.
代码:
from functools import wraps
DEBUG = True
def debug_log(function):
@wraps(function)
def wrapper(*args, **kwargs):
if DEBUG:
print(">> Called", function.__name__, "\n",
{**dict(zip(function.__code__.co_varnames, args)), **kwargs})
result = function(*args, **kwargs)
if DEBUG:
print(">>", function.__name__, "return:\n", result)
return result
return wrapper
@debug_log
def first_example(a, b, c):
return 100
@debug_log
def second_example(d, e, f):
return 200
first_example(10, 11, 12)
first_example(c=12, a=10, b=11)
second_example(13, 14, 15)
second_example(e=14, d=13, f=15)
DEBUG = False
first_example(0, 0, 0)
second_example(1, 1, 1)
输出:
>> Called first_example
{'a': 10, 'b': 11, 'c': 12}
>> first_example return:
100
>> Called first_example
{'c': 12, 'a': 10, 'b': 11}
>> first_example return:
100
>> Called second_example
{'d': 13, 'e': 14, 'f': 15}
>> second_example return:
200
>> Called second_example
{'e': 14, 'd': 13, 'f': 15}
>> second_example return:
200
这篇关于在Python中打印函数参数名称和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!