跳转到主要内容

一个点访问的字典(类似于JavaScript对象)

项目描述

Chunk是一个支持属性样式访问的字典,类似于JavaScript。

>>> b = Chunk()
>>> b.hello = 'world'
>>> b.hello
'world'
>>> b['hello'] += "!"
>>> b.hello
'world!'
>>> b.foo = Chunk(lol=True)
>>> b.foo.lol
True
>>> b.foo is b['foo']
True

字典方法

Chunk是dict的子类;它支持dict的所有方法

>>> b.keys()
['foo', 'hello']

包括 update()

>>> b.update({ 'ponies': 'are pretty!' }, hello=42)
>>> print repr(b)
Chunk(foo=Chunk(lol=True), hello=42, ponies='are pretty!')

以及迭代

>>> [ (k,b[k]) for k in b ]
[('ponies', 'are pretty!'), ('foo', Chunk(lol=True)), ('hello', 42)]

和“展开”

>>> "The {knights} who say {ni}!".format(**Chunk(knights='lolcats', ni='can haz'))
'The lolcats who say can haz!'

序列化

Chunk可以透明地序列化为JSON和YAML。

>>> b = Chunk(foo=Chunk(lol=True), hello=42, ponies='are pretty!')
>>> import json
>>> json.dumps(b)
'{"ponies": "are pretty!", "foo": {"lol": true}, "hello": 42}'

如果存在JSON支持(jsonsimplejson),Chunk将有一个 toJSON() 方法,它返回对象作为JSON字符串。

如果您已安装PyYAML,Chunk将尝试将自己注册到各种YAML表示器,以便Chunk可以透明地导出和加载。

>>> b = Chunk(foo=Chunk(lol=True), hello=42, ponies='are pretty!')
>>> import yaml
>>> yaml.dump(b)
'!chunk.Chunk\nfoo: !chunk.Chunk {lol: true}\nhello: 42\nponies: are pretty!\n'
>>> yaml.safe_dump(b)
'foo: {lol: true}\nhello: 42\nponies: are pretty!\n'

此外,Chunk 实例将有一个 toYAML() 方法,该方法使用 yaml.safe_dump() 返回 YAML 字符串。此方法还会替换(如果存在)__str__,因为我发现它更易读。您可以通过简单的赋值将 Chunk.__str__ 恢复到 Python 的默认使用 __repr__Chunk.__str__ = Chunk.__repr__。Chunk 类还将有一个静态方法 Chunk.fromYAML(),它可以从 YAML 字符串中加载 Chunk。

最后,Chunk 可以轻松递归地转换为(unchunkify()Chunk.toDict())和从(chunkify()Chunk.fromDict())一个普通 dict,这使得在其它格式中干净地序列化它们变得很容易。

杂项

  • 从该模块导入 import * 是安全的。您将获得: Chunkchunkifyunchunkify

  • 充足的 doctests

    $ python -m chunk.test
    $ python -m chunk.test -v | tail -n22
    1 items had no tests:
        chunk.fromYAML
    16 items passed all tests:
       8 tests in chunk
      13 tests in chunk.Chunk
       7 tests in chunk.Chunk.__contains__
       4 tests in chunk.Chunk.__delattr__
       7 tests in chunk.Chunk.__getattr__
       3 tests in chunk.Chunk.__repr__
       5 tests in chunk.Chunk.__setattr__
       2 tests in chunk.Chunk.fromDict
       2 tests in chunk.Chunk.toDict
       5 tests in chunk.chunkify
       2 tests in chunk.from_yaml
       3 tests in chunk.toJSON
       6 tests in chunk.toYAML
       3 tests in chunk.to_yaml
       3 tests in chunk.to_yaml_safe
       4 tests in chunk.unchunkify
    77 tests in 17 items.
    77 passed and 0 failed.
    Test passed.

反馈

GitHub 上打开工单 / 分支项目,或发送电子邮件至 dsc@less.ly

项目详情


下载文件

下载适合您平台的文件。如果您不确定选择哪个,请了解有关 安装包 的更多信息。

源分布

chunk-2.0.0.tar.gz (7.2 kB 查看哈希)

上传时间

由以下提供支持

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