将python kwargs保存回yaml的更安全或更pythonic方法?

时间:2018-07-17 08:12:13

标签: python yaml

这是一个非常抽象的示例,其中我从.yaml文件中存储的变量构建对象。我正在写反向方法,将它们另存为新的.yaml

我可以通过脚本创建其他对象,因此输出yaml通常会有所不同。

我正在使用.locals()从kwarg中构建字典,然后使用.pop()删除我不想保存的字典。

这似乎可以工作并且可以执行我想要的操作,但是我觉得它很丑。我是否错过了一种更好,更安全或更pythonic的方式来做到这一点?

我知道这里有泡菜和莳萝,但是对于当前问题,我想将其限制为读写Yamls。 (because

注意::如果以后添加属性,我不希望保存它们。这就是为什么我在实例化后立即创建ob.L的原因。

输入.yaml:

bob:
  args: {'x':1, 'y':2}
sue:
  args: {'x':3, 'y':4}

输出.yaml:

bob:
  args:
    x: 1
    y: 2
new:
  args:
    x: 5
    y: 6
sue:
  args:
    x: 3
    y: 4

当前脚本:

class A(object):
    wow = 77
    def __init__(self, name, x, y):
        self.name = name
        self.x = x
        self.y = y
        self.L = locals()
        self.L.pop('name')
        self.L.pop('self')

import yaml

with open('thing.yaml', 'r') as infile:
    d = yaml.load(infile)

obs = []
for name, info in d.items():
    ob = A(name, **info['args'])
    obs.append(ob)

newob = A('new', 5, 6)
obs.append(newob)

newob.ignore_me = 777   # this should not be saved

# rebuild the yaml
d = dict()
for ob in obs:
    info = dict()

    info['args'] = ob.L

    d[ob.name] = info

with open('newthing.yaml', 'w') as outfile:
    yaml.dump(d, outfile, default_flow_style=False, allow_unicode=True)

1 个答案:

答案 0 :(得分:-1)

我不明白您为什么要这样做。您需要做的就是加载YAML,添加新项,然后再次转储。

with open('thing.yaml', 'r') as infile:
    d = yaml.load(infile)
d['new'] = {'x': 5, 'y': 6}
with open('newthing.yaml', 'w') as outfile:
    yaml.dump(d, outfile, default_flow_style=False, allow_unicode=True)