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

查看:65
本文介绍了传递许多参数的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包中的方法获取其argspec,然后从全局"参数dict中过滤掉不必要的参数.看起来像下面的代码片段.

  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()使用参数键值对调用

  • key-value method: ext_method() is called using argument key-value pairs

    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忽略额外的参数:

    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个参数,开始仅传递 1个.

    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天全站免登陆