[英]How to use **kwargs to fill in format parameters automatically
I want to automate/simplyfy this: 我想自动化/简化:
def test(stream, tag):
subprocess.call('git submodule checkout {stream}-{tag}'.format(stream=stream, tag=tag))
ie I want to get rid of stream=stream and tag=tag and somehow make use of something like **kwargs. 即我想摆脱stream = stream和tag = tag,并以某种方式利用** kwargs之类的东西。 Is this possible?
这可能吗?
My 2 cents: don't abuse **kwargs
, it should be used only if the number of parameters is not known a priori . 我的2美分:请不要滥用
**kwargs
,只有在先验未知参数数量的情况下才应使用它。
Here are some approaches not involving **kwargs
: 以下是一些不涉及
**kwargs
:
If your concern is length of line, you can save space by using implicit order: 如果您关心的是行长,则可以使用隐式顺序来节省空间:
def test(stream, tag):
subprocess.call('git submodule checkout {}-{}'.format(stream, tag))
This comes at the price of format string readability, but for a one-liner it might just do it. 这是以格式字符串可读性为代价的,但是对于单行代码而言,它可能只是这样做。
Wrap the parameters in a Checkout
object: 将参数包装在
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))
or even: 甚至:
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))
This is verbose, but the Checkout
object is more than a simple wrapper, it might be reused somewhere else or serialized. 这很冗长,但是
Checkout
对象不仅仅是一个简单的包装器,它可能在其他地方重用或序列化。
this should work: 这应该工作:
def test(**kwargs):
subprocess.call("git submodule checkout {stream}-{tag}".format(**kwargs))
Now, you could add some default values, or raise clearer error messages. 现在,您可以添加一些默认值,或者引发更清晰的错误消息。
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))
Now, when the tag argument is not set, the message will tell you so. 现在,当未设置tag参数时,消息将告诉您。 Without this code, the only information you get is a KeyError with the name of the missing key.
没有此代码,您获得的唯一信息就是KeyError以及丢失的键的名称。
You could use locals()
to pass the dictionary of local variables: 您可以使用
locals()
传递局部变量的字典:
def test(stream, tag):
subprocess.call('git submodule checkout {stream}-{tag}'.format(**locals()))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.