首页 > 解决方案 > 简化重复使用参数的调用签名

问题描述

我有一堆具有相似输入的函数。这意味着有一个重复出现的标准参数列表,其中一些可能会有所不同:

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 调用一些东西,arg2std_arg2 想整理代码,现在的问题是这里最干净的方法是什么。理想情况下,我想要类似的东西:

def super_f(all_the_args):
   # depending on some args call eventually
   f3(all_the_args)

wheref3再次用all_the_args. 或者至少包含一些论据。虽然这可能不好读或效率低下(我不知道)。

我的想法是:

  1. 收集列表中的部分或全部参数并在函数中“解包”它们:
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
  1. 将它们收集在字典中,例如:
std_args = {"std_arg1": std_val1, "std_arg2": std_val2, ...}
def f1(arg, std_args):
    # rewrite "std_arg1" -> std_args["std_arg1"]
  1. 将所有参数放在全局范围内,这样每个函数都知道,这对我来说听起来很脏,我必须在每个模块/文件中都这样做。

  2. 使用带有 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 可能会在整个“级别”/文件中更轻松地完成。

这个问题有更好的解决方案吗?或者有什么建议如何以更好的结构编写这段代码?

标签: pythonsignature

解决方案


推荐阅读