跳转到主要内容

一个点访问的字典(类似于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支持(jsonsimplejson),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 * 是安全的。您将获得:Bunchbunchifyunbunchify

  • 丰富的 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 (7.3 kB 查看散列)

上传时间

由以下支持

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误日志 StatusPage StatusPage 状态页面