Alex Kessinger changelog.com/posts

Bunch lets you use a Python dict like it's an Object

Sometimes, in Python, I wish I could access dicts as if they are objects. Bunch makes it easy to do that.

A Bunch is a Python dictionary that provides attribute-style access (a la JavaScript objects).

Bunch acts like an object and a dict.

>>> b = Bunch()
>>> b.hello = 'world'
>>> b.hello
'world'
>>> b['hello'] += "!"
>>> b.hello
'world!'

And it even plays nice with serialization.

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

This approach isn't for everything, but if you want a dict that acts like an object checkout Bunch.


Discussion

Sign in or Join to comment or subscribe

Player art
  0:00 / 0:00