一个点访问的字典(类似于JavaScript对象)
项目描述
Bunch是一种字典,支持类似JavaScript的属性式访问。
>>> b = Bunch() >>> b.hello = 'world' >>> b.hello 'world' >>> b['hello'] += "!" >>> b.hello 'world!' >>> b.foo = Bunch(lol=True) >>> b.foo.lol True >>> b.foo is b['foo'] True
字典方法
Bunch是dict的子类;它支持dict的所有方法
>>> b.keys() ['foo', 'hello']
包括 update()
>>> b.update({ 'ponies': 'are pretty!' }, hello=42) >>> print repr(b) Bunch(foo=Bunch(lol=True), hello=42, ponies='are pretty!')
以及迭代
>>> [ (k,b[k]) for k in b ] [('ponies', 'are pretty!'), ('foo', Bunch(lol=True)), ('hello', 42)]
还有“展开”操作
>>> "The {knights} who say {ni}!".format(**Bunch(knights='lolcats', ni='can haz')) 'The lolcats who say can haz!'
序列化
Bunch可以愉快且透明地序列化为JSON和YAML。
>>> b = Bunch(foo=Bunch(lol=True), hello=42, ponies='are pretty!') >>> import json >>> json.dumps(b) '{"ponies": "are pretty!", "foo": {"lol": true}, "hello": 42}'
如果存在JSON支持(json或simplejson),Bunch将有一个toJSON()方法,该方法返回一个JSON字符串。
如果您已安装PyYAML,Bunch会尝试将自己注册到各种YAML表示器中,以便Bunch可以被透明地存档和加载。
>>> b = Bunch(foo=Bunch(lol=True), hello=42, ponies='are pretty!') >>> import yaml >>> yaml.dump(b) '!bunch.Bunch\nfoo: !bunch.Bunch {lol: true}\nhello: 42\nponies: are pretty!\n' >>> yaml.safe_dump(b) 'foo: {lol: true}\nhello: 42\nponies: are pretty!\n'
此外,Bunch实例将有一个toYAML()方法,它使用yaml.safe_dump()返回YAML字符串。如果存在,此方法还将替换__str__,因为我认为它更易于阅读。您可以通过简单的赋值将Bunch.__str__还原为Python的默认使用__repr__: Bunch.__str__ = Bunch.__repr__。Bunch类还将有一个静态方法Bunch.fromYAML(),它可以从YAML字符串中加载Bunch。
最后,Bunch 可以轻松地递归转换为 (unbunchify(),Bunch.toDict()) 以及从 (bunchify(),Bunch.fromDict()) 正常的 dict 中转换,这使得它们在其他格式中易于干净地序列化。
杂项
从这个模块中导入 import * 是安全的。您将获得:Bunch,bunchify 和 unbunchify。
丰富的 doctests
$ python -m bunch.test $ python -m bunch.test -v | tail -n22 1 items had no tests: bunch.fromYAML 16 items passed all tests: 8 tests in bunch 13 tests in bunch.Bunch 7 tests in bunch.Bunch.__contains__ 4 tests in bunch.Bunch.__delattr__ 7 tests in bunch.Bunch.__getattr__ 3 tests in bunch.Bunch.__repr__ 5 tests in bunch.Bunch.__setattr__ 2 tests in bunch.Bunch.fromDict 2 tests in bunch.Bunch.toDict 5 tests in bunch.bunchify 2 tests in bunch.from_yaml 3 tests in bunch.toJSON 6 tests in bunch.toYAML 3 tests in bunch.to_yaml 3 tests in bunch.to_yaml_safe 4 tests in bunch.unbunchify 77 tests in 17 items. 77 passed and 0 failed. Test passed.
反馈
在 GitHub 上打开工单 / 分叉项目,或者发送电子邮件至 dsc@less.ly。
项目详情
关闭
infi.bunch-2.0.0.tar.gz 的散列
算法 | 散列摘要 | |
---|---|---|
SHA256 | 76a655ae3fa4a27a3233f5f18440ba4cb3023af08d0355a4fb3584e26f9eaebb |
|
MD5 | 1dfc0ea092ad5aa5641d7413169a1e65 |
|
BLAKE2b-256 | cf95dc268b05012ddaf5e0e120bd59521f69a4dba2b6595541c12fbd2ad718d5 |