一个点可访问的字典(一个la javascript对象)
infi.bunch的Python项目详细描述
bunch是一个支持属性样式访问的字典,一个la 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的一个子类;它支持adict所做的所有方法:
>>> 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)]
和“splats”:
>>> "The {knights} who say {ni}!".format(**Bunch(knights='lolcats', ni='can haz')) 'The lolcats who say can haz!'
序列化
愉快地和透明地串接到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__,因为我发现它更具可读性。您可以通过一个简单的赋值返回到python默认使用的__repr__。bunch类还有一个静态方法Bunch.fromYAML(),它从yaml字符串中加载一个bunch。
最后,bunch可以方便地递归地转换为(unbunchify(),Bunch.toDict())和(bunchify(),Bunch.fromDict())一个普通的dict,这样就很容易以其他格式对它们进行干净的序列化。
其他
从这个模块import *是安全的。您将得到:Bunch、bunchify和unbunchify。
大量的博士学位:
$ 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向我发送电子邮件。