如何使用** kwargs自动填写格式参数

时间:2013-05-14 23:11:39

标签: python

我想自动化/简单地解决这个问题:

def test(stream, tag):
    subprocess.call('git submodule checkout {stream}-{tag}'.format(stream=stream, tag=tag))

即。我想摆脱stream = stream和tag = tag,并以某种方式利用像** kwargs这样的东西。这可能吗?

3 个答案:

答案 0 :(得分:4)

我的2美分:不要滥用**kwargs,只有在参数数量未知 a priori 时才应该使用它。

以下是一些不涉及**kwargs的方法:

如果您的关注点是行长,则可以使用隐式顺序来节省空间:

def test(stream, tag):
    subprocess.call('git submodule checkout {}-{}'.format(stream, tag))

这是以格式字符串可读性为代价的,但对于单行代码,它可能只是这样做。

对象样式

将参数包装在Checkout对象中:

class Checkout:
    def __init__(self, stream, tag):
        self.stream = stream
        self.tag = tag

#...

def test(checkout):
    subprocess.call('git submodule checkout {0.stream}-{0.tag}'.format(checkout))

甚至:

class Checkout:
    def __init__(self, stream, tag):
        self.stream = stream
        self.tag = tag

    def test(self):
        subprocess.call('git submodule checkout {0.stream}-{0.tag}'.format(self))

这是冗长的,但Checkout对象不仅仅是一个简单的包装器,它可能会在其他地方重复使用或序列化。

答案 1 :(得分:2)

这应该有效:

def test(**kwargs):
    subprocess.call("git submodule checkout {stream}-{tag}".format(**kwargs))

现在,您可以添加一些默认值,或者提出更清晰的错误消息。

def test(**kwargs):
    #set a default value for "stream"
    if "stream" not in kwargs:
        kwargs["stream"] = "mystream"
    if "tag" not in kwargs:
        raise ValueError("Please add some tags")
    subprocess.call("git submodule checkout {stream}-{tag}".format(**kwargs))

现在,当未设置tag参数时,该消息将告诉您。如果没有此代码,您获得的唯一信息是KeyError,其中包含缺失密钥的名称。

答案 2 :(得分:0)

您可以使用locals()传递局部变量字典:

def test(stream, tag):
    subprocess.call('git submodule checkout {stream}-{tag}'.format(**locals()))