[英]is it safe and/or pythonic to directly overwrite dict entries in the constructor?
I'm storing some configuration state in a dictionary, where a bunch of separate FFMPEG filters share a common set of parameters, and then we change/override those for each specific filter.我将一些配置状态存储在字典中,其中一堆单独的 FFMPEG 过滤器共享一组通用参数,然后我们更改/覆盖每个特定过滤器的参数。 My current code looks like this, and appears to work....
我当前的代码看起来像这样,并且似乎可以工作....
default['common']['fontfile'] = '/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf'
default['common']['rate'] = framerate
default['common']['fontcolor'] = 'yellow'
default['common']['box'] = 1
default['common']['y'] = 0 # x and y are offsets from the top left of frame
default['common']['x'] = 0
then I'm just calling another constructor with the ** operator to pull all those common keys/values into my new dict, as well as add some new k/v pairs and make some changes to the existing k/v pairs.然后我只是使用 ** 运算符调用另一个构造函数,将所有这些公共键/值拉入我的新字典,以及添加一些新的 k/v 对并对现有的 k/v 对进行一些更改。
In this example I'm changing the values for 'x'
and 'y'
and adding 'start_number' : 0
to the dict:在这个例子中,我改变了
'x'
和'y'
,并将'start_number' : 0
添加到字典中:
default['framectr'] = {
**default['common'],
'y' : (vid_h * 0.2),
'x' : (vid_w * 0.2),
'start_number' : 0
}
So far this appears to work, but are there potential side effects here I should be worried about?到目前为止,这似乎有效,但是我应该担心这里有潜在的副作用吗? I considered just making a
deepcopy()
of the original/common dict and then adding/modifying the entries that way, but at least to my inexperienced eye the constructor call seems cleaner.我考虑过只制作原始/通用字典的
deepcopy()
,然后以这种方式添加/修改条目,但至少在我没有经验的眼中,构造函数调用似乎更清晰。
Thoughts?想法?
Semantically,语义上,
default['framectr'] = {
**default['common'],
'y' : (vid_h * 0.2),
'x' : (vid_w * 0.2),
'start_number' : 0
}
is equivalent to相当于
default['framectr'] = {
'fontfile': default['common']['fontfile'],
'rate': default['common']['rate'],
'fontcolor': default['common']['fontcolor'],
'box': default['common']['box'],
'y': default['common']['y'],
'x': default['common']['x'],
'y' : (vid_h * 0.2),
'x' : (vid_w * 0.2),
'start_number' : 0
}
Neither is safer or more dangerous than the other in terms of side effects.就副作用而言,两者都不比另一个更安全或更危险。 Given that you aren't using any mutable values in the definition of
default['common']
, making a deep copy won't buy you anything.鉴于您没有在
default['common']
的定义中使用任何可变值,制作深层副本不会给您带来任何好处。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.