3

Using bunch, can Bunch be used recursively?

For example:

from bunch import Bunch
b = Bunch({'hello': {'world': 'foo'}})
b.hello
>>> {'world': 'foo'}

So, obviously:

b.hello.world
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-5-effaad77643b> in <module>()
----> 1 b.hello.world

AttributeError: 'dict' object has no attribute 'world'

I know I could do...

b = Bunch({'hello': Bunch({'world': 'foo'})})

...but that's awful.

Peter Wood
  • 23,859
  • 5
  • 60
  • 99
joedborg
  • 17,651
  • 32
  • 84
  • 118

2 Answers2

4

Dug into the source code, this can be done with the fromDict method.

b = Bunch.fromDict({'hello': {'world': 'foo'}})
b.hello.world
>>> 'foo'
joedborg
  • 17,651
  • 32
  • 84
  • 118
2

Bunch.fromDict could do this magic for you:

>>> d = {'hello': {'world': 'foo'}}
>>> b = Bunch.fromDict(d)
>>> b
Bunch(hello=Bunch(world='foo'))
>>> b.hello
Bunch(world='foo')
>>> b.hello.world
'foo'
Mureinik
  • 297,002
  • 52
  • 306
  • 350