dict扩展munch,支持yaml文件

 

安装:pip install munch

用法参考:https://github.com/Infinidat/munch

 

Munch is a dictionary that supports attribute-style access, a la JavaScript.意思是支持"a.b"的写法获取属性值

In [4]: from munch import Munch

In [5]: b=Munch()

In [6]: b.hello='world'

In [7]: b
Out[7]: Munch({'hello': 'world'})

In [8]: b.hello
Out[8]: 'world'

In [9]: b.hello+="!"

In [10]: b
Out[10]: Munch({'hello': 'world!'})

In [11]: b.fool=Munch(lol=True)

In [12]: b
Out[12]: Munch({'hello': 'world!', 'fool': Munch({'lol': True})})

In [13]: b.fool
Out[13]: Munch({'lol': True})

In [14]: b.fool.lol
Out[14]: True


In [16]: b['fool'] Out[16]: Munch({'lol': True}) In [17]: b['fool']['lol'] Out[17]: True In [18]: b['fool'].lol Out[18]: True

 

自然也是支持字典的各种用法:

In [19]: b.keys()
Out[19]: dict_keys(['hello', 'fool'])

In [20]: b.update({'ponies':'are prettty!'},hello=42)

In [21]: b
Out[21]: Munch({'hello': 42, 'ponies': 'are prettty!', 'fool': Munch({'lol': True})})

In [22]: print(repr(b))
Munch({'hello': 42, 'ponies': 'are prettty!', 'fool': Munch({'lol': True})})

In [23]: [ (k,b[k]) for k in b ]
Out[23]: [('hello', 42), ('ponies', 'are prettty!'), ('fool', Munch({'lol': True}))]

In [24]: "The {knights} who say {ni}!".format(**Munch(knights='lolcats', ni='can haz'))
Out[24]: 'The lolcats who say can haz!'

In [25]: "The {knights} who say {ni}!".format(**{'knights':'test','ni':'wo'})
Out[25]: 'The test who say wo!'

使用json和yaml实现序列化:

In [26]: b = Munch(foo=Munch(lol=True), hello=42, ponies='are pretty!')

In [27]: import json

In [28]: json.dumps(b)
Out[28]: '{"hello": 42, "ponies": "are pretty!", "foo": {"lol": true}}'

In [29]: import yaml

In [30]: yaml.dump(b)
Out[30]: '!munch.Munch\nfoo: !munch.Munch {lol: true}\nhello: 42\nponies: are pretty!\n'

In [31]: yaml.safe_dump(b)
Out[31]: 'foo: {lol: true}\nhello: 42\nponies: are pretty!\n'

Default Values

DefaultMunch instances return a specific default value when an attribute is missing from the collection. Like collections.defaultdict, the first argument is the value to use for missing keys:

>>> undefined = object()
>>> b = DefaultMunch(undefined, {'hello': 'world!'})
>>> b.hello
'world!'
>>> b.foo is undefined
True

DefaultMunch.fromDict() also takes the default argument:

>>> undefined = object()
>>> b = DefaultMunch.fromDict({'recursively': {'nested': 'value'}}, undefined)
>>> b.recursively.nested == 'value'
True
>>> b.recursively.foo is undefined
True

Or you can use DefaultFactoryMunch to specify a factory for generating missing attributes. The first argument is the factory:

>>> b = DefaultFactoryMunch(list, {'hello': 'world!'})
>>> b.hello
'world!'
>>> b.foo
[]
>>> b.bar.append('hello')
>>> b.bar
['hello']

 

posted @ 2019-02-14 11:03  脚本小娃子  阅读(575)  评论(0编辑  收藏  举报