跳转到主要内容

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

项目描述

Latest Version Supported Python versions Downloads

munch

安装

pip install munch

使用

munch是David Schoonover的Bunch软件包的分支,提供类似的功能。99%的工作由他完成,分支主要是为了缺乏对原始代码的修复和维护的响应。

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

>>> from munch import Munch
>>> b = Munch()
>>> b.hello = 'world'
>>> b.hello
'world'
>>> b['hello'] += "!"
>>> b.hello
'world!'
>>> b.foo = Munch(lol=True)
>>> b.foo.lol
True
>>> b.foo is b['foo']
True

字典方法

“Munch” 是 dict 的子类;它支持所有 dict 的方法

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

包括 update()

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

以及迭代

>>> [ (k,b[k]) for k in b ]
[('hello', 42), ('foo', Munch({'lol': True})), ('ponies', 'are pretty!')]

和“splat”

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

序列化

Munch 可以愉快且透明地将数据序列化为 JSON 和 YAML 格式。

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

如果存在 JSON 支持(jsonsimplejson),Munch 将拥有一个 toJSON() 方法,该方法返回一个 JSON 字符串。

如果您已安装 PyYAML,Munch 会尝试将自己注册到各种 YAML 表示器,以便 Munch 对象可以被透明地保存和加载。

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

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

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

默认值

DefaultMunch 实例在集合中缺少属性时返回一个特定的默认值。与 collections.defaultdict 类似,第一个参数是用于缺失键的值

>>> from munch import DefaultMunch
>>> undefined = object()
>>> b = DefaultMunch(undefined, {'hello': 'world!'})
>>> b.hello
'world!'
>>> b.foo is undefined
True

DefaultMunch.fromDict() 也接受 default 参数

>>> undefined = object()
>>> b = DefaultMunch.fromDict({'recursively': {'nested': 'value'}}, undefined)
>>> b.recursively.nested == 'value'
True
>>> b.recursively.foo is undefined
True

或者,您可以使用 DefaultFactoryMunch 来指定生成缺失属性的工厂。第一个参数是工厂

>>> from munch import DefaultFactoryMunch
>>> b = DefaultFactoryMunch(list, {'hello': 'world!'})
>>> b.hello
'world!'
>>> b.foo
[]
>>> b.bar.append('hello')
>>> b.bar
['hello']

杂项

  • 从该模块导入 import * 是安全的。您将获得:MunchDefaultMunchDefaultFactoryMunchmunchifyunmunchify
  • 充足的测试。只需从项目根目录运行 pip install tox && tox

反馈

GitHub 上创建工单/分支项目。

项目详情


下载文件

下载适合您平台的应用程序。如果您不确定选择哪个,请了解更多关于 安装包 的信息。

源分发

munch-4.0.0.tar.gz (19.1 kB 查看哈希值)

上传时间

构建分发

munch-4.0.0-py2.py3-none-any.whl (9.9 kB 查看哈希值)

上传时间 Python 2 Python 3

支持