【发布时间】:2021-03-05 11:50:31
【问题描述】:
我目前正在努力以一种干净的方式在 python 中记录一个函数。
假设我想记录一个函数,它有一个不起眼的 list_of_numbers 作为参数。
def function_to_log(list_of_numbers):
# manipulate the values in list_of_numbers ...
return some_result_computed_from_list_of_numbers
当list_of_numbers 中的值在上述函数中被操作时,我想记录该更改,但不是使用晦涩的list_of_numbers 中的值,而是第二个列表@987654325 中相同索引处的值@。
让我烦恼的事情:现在我还必须输入list_with_names_for_log,这会使我的函数的参数列表膨胀,
def function_to_log(list_of_numbers, list_with_names_for_log):
# do some stuff like, change value on 3rd index:
list_of_numbers[3] = 17.4
log.info('You have changed {} to 17.4'.format(list_with_names_for_log[3]))
# and so on ...
return some_result_computed_from_list_of_numbers
我使用这些列表中的多个专门用于登录此功能。 有没有人知道如何让它更干净一点?
【问题讨论】:
-
可用于
list_with_names_for_log参数的列表是否与函数在同一范围内?调用表达式如何决定使用哪个列表? -
是的,列表驻留在一个调用
function_to_log的母函数中,并将它们作为额外的参数。要使用哪个列表在function_to_log中硬编码:对于某些操作,我只使用一个list_with_names进行日志记录,对于某些操作,这些列表的组合。 -
您的问题中可能没有足够的细节来为您的情况提供足够的解决方案。正如 Carcigenicate 指出的那样,您有成对的列表,这些列表通过它们的索引关联,因此 Carcigenicate 的解决方案可能会解决您拥有不需要的 extra 函数参数的问题。如果返回值和参数之间存在关系,您可以检查返回值并在调用函数中进行日志记录。也许使用数据值的描述符并设计描述符以在更改时记录。或者 Carcigenicate 的 NamedData 类可以设计为在更改时记录。
标签: python logging functional-programming