一个点访问的字典(类似于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支持(json或simplejson),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 * 是安全的。您将获得: Chunk,chunkify 和 unchunkify。 
- 充足的 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 的哈希
| 算法 | 哈希摘要 | |
|---|---|---|
| SHA256 | 916ff1d96b99f27651d939155b9ede95c6e597d047f408ec6a256cb8fd6a2033 | |
| MD5 | 1aa85ccc0d9cf76f3f9c85c809aeebf4 | |
| BLAKE2b-256 | 07c3397e29e963894fdf66b7a697454e92bbb422d5275c23384b611875d3eea2 |