我认为加载一些 YAML 对象是一个小误解。我定义了下面的类。
我想要做的是加载一些具有覆盖loadConfig
函数的对象YAMLObjects
。其中一些来自我的.yaml
文件,但其他应该由从 YAML 文件加载的对象构建而成。
例如,在下面的类中,我加载了一个名为“keep”的成员对象,它是一个字符串,用于命名要保留在该区域中的一些项目。但我也想将其解析为一个列表,并将该列表也存储为成员对象。而且我不希望用户必须在 YAML 中同时提供此参数的字符串和列表版本。
我目前的工作是覆盖__getattr__
里面的函数Region
,如果它看起来没有找到它们,让它创建默认值。但这比初始化对象所需要的笨重和复杂。
我在这里误解了什么约定。为什么该loadConfig
方法不创建 YAML 中没有的其他内容?
import yaml, pdb
class Region(yaml.YAMLObject):
yaml_tag = u'!Region'
def __init__(self, name, keep, drop):
self.name = name
self.keep = keep
self.drop = drop
self.keep_list = self.keep.split("+")
self.drop_list = self.drop.split("+")
self.pattern = "+".join(self.keep_list) + "-" + "-".join(self.drop_list)
###
def loadConfig(self, yamlConfig):
yml = yaml.load_all(file(yamlConfig))
for data in yml:
# These get created fine
self.name = data["name"]
self.keep = data["keep"]
self.drop = data["drop"]
# These do not get created.
self.keep_list = self.keep.split("+")
self.drop_list = self.drop.split("+")
self.pattern = "+".join(self.keep_list) + "-" + "-".join(self.drop_list)
###
### End Region
if __name__ == "__main__":
my_yaml = "/home/path/to/test.yaml"
region_iterator = yaml.load_all(file(my_yaml))
# Set a debug breakpoint to play with region_iterator and
# confirm the extra stuff isn't created.
pdb.set_trace()
在这里test.yaml
,你可以运行所有这些,看看我的意思:
Regions:
# Note: the string conventions below are for an
# existing system. This is a shortened, representative
# example.
Market1:
!Region
name: USAndGB
keep: US+GB
drop: !!null
Market2:
!Region
name: CanadaAndAustralia
keep: CA+AU
drop: !!null
例如,这里是我在 IPython shell 中运行它并探索加载的对象时的样子:
In [57]: %run "/home/espears/testWorkspace/testRegions.py"
--Return--
> /home/espears/testWorkspace/testRegions.py(38)<module>()->None
-> pdb.set_trace()
(Pdb) region_iterator
<generator object load_all at 0x1139d820>
(Pdb) tmp = region_iterator.next()
(Pdb) tmp
{'Regions': {'Market2': <__main__.Region object at 0x1f858550>, 'Market1': <__main__.Region object at 0x11a91e50>}}
(Pdb) us = tmp['Regions']['Market1']
(Pdb) us
<__main__.Region object at 0x11a91e50>
(Pdb) us.name
'USAndGB'
(Pdb) us.keep
'US+GB'
(Pdb) us.keep_list
*** AttributeError: 'Region' object has no attribute 'keep_list'