在你解释了如何应用这个之后,我认为最好的方法是使用
decorator
. 它是一个更通用的解决方案,因为您可以将它添加到代码中的任何函数中,并且如果启用调试模式,它将打印所有调试信息。
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