简体   繁体   English

Python方便地将字典参数传递给函数

[英]Python convenient passing of dictionary arguments to function

I thought about attaching the dictionary to the local scope somehow, however I have seen similar questions asked on SO - usually with the response 'don't do it!'. 我曾考虑过以某种方式将字典附加到本地范围,但是我也看到了类似的问题,通常是回答“不要这样做!”。 I will illustrate my problem and welcome any suggestions to overcome this. 我将说明我的问题,并欢迎提出任何克服此问题的建议。

If have an options dictionary (read from JSON so prefer not to have to mess to much with it) and I have decided to pass this as follows; 如果有一个选项字典(从JSON读取,那么最好不要对它进行太多修改),我决定按以下方式传递它:

def testParse(dataObj, userOptions):

    # Merge default with passed options taking prescidence
    defaultOpts = {

        'boxheight' : 200,
        'boxwidth'  : 100,
        'padding'   : 150

    }
    opt = dict(userOptions.items() | defaultOpts.items())

The question is; 问题是; Is there any way to attach each value in the dictionary to the local scope using the key so that rather than copying out the entire dictionary 有什么方法可以使用键将字典中的每个值附加到本地范围,而不是复制整个字典

boxheight = opt['boxheight']

etc., or writing opt['boxheight'] every time I refer to it. 等等,或者每次我引用它时都写opt['boxheight'] Can I just loop the opt dictionary and assign the value programatically? 我可以循环opt字典并以编程方式分配值吗?

I am in no way attached to the approach outlined, but all options will be used in local expressions at some point and they exist from the outset as a dictionary. 我绝对不喜欢所概述的方法,但是所有选项都会在局部表达式中使用,并且它们从一开始就作为字典存在。 Many thanks in advance for your suggestions. 在此先非常感谢您的建议。

[Disclaimer: Only been working with Python for a few days] [免责声明:仅使用Python已有几天时间]

Ok, thanks to @jonrshapre's comment I have the following solution 好的,感谢@jonrshapre的评论,我有以下解决方案

# user options
userOps = { 'name' : 'joe', 'age' : 21 }
data = (1,2)

# default options specified as function argument
def _func(data, name, lovesSO = True, **kwargs):

    print(data)
    print(name)
    print(lovesSO)
    print(kwargs)

# Call
_func(data, **userOps)    

# OUTPUTS
# (1,2)
# joe
# True
# {'age' : 21}

The price to pay with this approach appears to be the slightly unconventional calling syntax (although as pointed out in the comments this is only unusual to a newbee like me). 这种方法要付出的代价似乎是稍微非常规的调用语法(尽管正如注释中指出的那样,这仅对像我这样的新手而言是不寻常的)。 However this can be fixed up by defining 但是,可以通过定义

def func(data, options): _func(data, **options)

Or another solution based upon @ Sven Marnach's comment; 或基于@ Sven Marnach的评论的其他解决方案;

# Utility options class
class Options:
    def __init__(self, defaults, user_opts):
        vars(self).update(defaults)
        vars(self).update(user_opts)

def func2(data, userOps):

    opt = Options({ 'lovesSO' : True}, userOps)

    print(data)
    print(opt.name)
    print(opt.lovesSO)

# Call    
func2(data, userOps)

# OUTPUT
# (1, 2)
# joe
# True

This has the drawback of defining a helper class but has the benefit of clearly knowing which variables are user definable options by the presence of the opt. 这具有定义助手类的缺点,但具有通过opt.的存在清楚地知道哪些变量是用户可定义的选项的优点opt. prefix. 字首。 In addition the calling syntax is natural. 另外,调用语法是自然的。

In both cases, unused user options are stored as either the kwargs dictionary (in the first case) or as unused entries in the opt dictionary. 在这两种情况下,未使用的用户选项都存储为kwargs字典(在第一种情况下)或opt字典中的未使用条目。

Personally I have decided to opt for the second solution. 我个人决定选择第二种解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM