python - 简化重复使用参数的调用签名
问题描述
我有一堆具有相似输入的函数。这意味着有一个重复出现的标准参数列表,其中一些可能会有所不同:
def f1(arg, std_arg1, std_arg2, ...):
# do something
def f2(another_arg, std_arg1, std_arg2, ...):
# do something else
我现在想通过包含所有参数的列表或字典来简化调用签名。这样更容易调用所有不同的函数,也更容易编写新函数。这个问题越来越严重,因为函数可能会从其他模块/文件调用其他函数,其签名又包含许多这些参数,例如:
def super_f(arg1, arg2, std_arg1, std_arg2, ...):
# depending on some args call eventually
f3(arg2, std_arg1, std_arg2, ...)
, wheref3
再次用 eg 调用一些东西,arg2
我std_arg2
想整理代码,现在的问题是这里最干净的方法是什么。理想情况下,我想要类似的东西:
def super_f(all_the_args):
# depending on some args call eventually
f3(all_the_args)
wheref3
再次用all_the_args
. 或者至少包含一些论据。虽然这可能不好读或效率低下(我不知道)。
我的想法是:
- 收集列表中的部分或全部参数并在函数中“解包”它们:
std_args = [std_arg1, std_arg2, std_arg3, ...] # or potentially all the args
def f(arg, std_args):
std_arg1, std_arg2, ... = std_args
# do something
- 将它们收集在字典中,例如:
std_args = {"std_arg1": std_val1, "std_arg2": std_val2, ...}
def f1(arg, std_args):
# rewrite "std_arg1" -> std_args["std_arg1"]
将所有参数放在全局范围内,这样每个函数都知道,这对我来说听起来很脏,我必须在每个模块/文件中都这样做。
使用带有 list 或 dict 的类作为构造函数的输入,其中存储所有参数,然后在该范围内知道。
def class func(object):
def __init__(self, std_args):
self.std_arg1 = std_args[0]
self.std_arg2 = std_args[1]
...
def f1(self, arg):
# do something with arg, std_arg1, std_arg2, ...
这可能是最干净的解决方案,但需要一些重写(好吧,可能只是一些 find->replace)并且我的代码中有很多ulgy self.
。
对于选项 1、2、3,我认为我必须在调用结构的每个“级别”上执行此操作。选项 4 可能会在整个“级别”/文件中更轻松地完成。
这个问题有更好的解决方案吗?或者有什么建议如何以更好的结构编写这段代码?
解决方案
推荐阅读
- flutter - 如何在颤动中选择多个日期?
- android - Flutter 插件:将数据从 Android BroadcastReceiver 发送到 Flutter 代码
- javascript - 当我尝试在前一个元素之后选择第一个 ul 元素时,兄弟选择器和第一个类型不起作用
- laravel-5.8 - Laravel 5.8 voyager 翻译器在分页时不起作用
- javascript - 如何使用 map() 获取字符串列表的当前行
- c++ - 为什么我在 codechef ide 上收到 SIGCONT 错误?
- python-3.x - Wkhtmltopdf 失败(错误代码:-11)。内存限制太低或达到子进程的最大文件数。消息:b'' Odoo 14 CE
- azure - 如何编写 Kusto 查询以在哨兵中获取上个月的日志?
- twilio - Twilio 电话验证 API 自定义名称和消息
- google-sheets - 修改 BigQuery 外部表中的架构(谷歌表格)