传递许多参数的 Pythonic 方式 [英] Pythonic way to pass around many arguments

查看:31
本文介绍了传递许多参数的 Pythonic 方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个包含子包和每个子包中的几个模块的包.大多数函数需要在main"函数中启动的几个参数(~10).通常,所有参数都传递给从函数内部调用的方法.传递这些参数的最佳方式是什么?

I'm working on a package that contains subpackages and several modules within each subpackage. Most of the functions need several arguments (~10) that are initiated in the "main" function. Usually, all the arguments are passed to methods that are called from within a function. What is the best way to pass around these parameters ?

考虑以下场景:

def func(arg1, arg2, ...., argn):
  do something  
  ext_method(arg1, arg3,...argk) # Note: all the arguments are not passed to ext_method
  cleanup  

PS:函数嵌套可以很深(比如从主函数开始大约有 10-12 个函数).我考虑了两种选择:

PS: Function nesting can go quite deep (say around 10-12 functions starting from main function). I considered two alternatives:

  1. Inspect 方法:构造一个包含所有参数的主函数中的所有参数的字典.调用函数:使用inspect包中的方法获取其argspec,并从全局"参数字典中过滤掉不必要的参数.它看起来像下面的代码片段.

  1. Inspect method: Construct a dict of all the arguments in the main function with all the arguments. To call a function: Get its argspec using the method in inspect package, and filter out unnecessary arguments from the "global" arguments dict. It looks something like the below snippet.

args = {arg1: obj1, arg2:obj2,...}  
req_args = dict([(k, v) for k, v in args.items() if k in inspect.getargspec(ext_method).args])

  • 键值方法:ext_method() 使用参数键值对调用

    ext_method(arg1=val1, arg3=val3,...,argk=valk)
    

  • 我发现第二种方法无效,因为随着更多功能添加到包中,它不容易更改 ext_method() 的签名.方法 1 是更好的选择吗?

    I find the second method to be ineffective because its not easy to change the signature of ext_method() as more features are added to the package. Is method 1 a better alternative ?

    推荐答案

    更多更好的选择:

    1. **kwargs 添加到您的函数并忽略额外的参数:

    1. Add **kwargs to your functions and ignore extra arguments:

    ex_method(arg1, arg2, **kw)
    

  • 将所有参数作为属性传递给对象;namedtuple 将是理想的这里.每个函数只使用它需要的那些属性.

  • Pass around an object with all arguments as attributes; a namedtuple class would be ideal here. Each function only uses those attributes it needs.

    我会选择后者.停止围绕 10 个参数移动,开始只传递一个.

    I'd pick the latter. Stop moving around 10 arguments, start passing around just one.

    更好的是,如果所有这些操作真的与这些参数所代表的数据耦合,也许您应该使用一个类来代替:

    Even better, if all those operations are really coupled to the data those arguments represent, perhaps you should be using a class instead:

    class SomeConcept(object):
        def __init__(self, arg1, arg2, arg3, .., argN):
            self.arg1 = arg1
            # ... etc.
    
        def operation1(self, external_argument):
            # use `self` attributes, return something.
    

    而不是所有那些单独的功能.

    instead of all those separate functions.

    这篇关于传递许多参数的 Pythonic 方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆