Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Python's Bunch be used recursively?

Tags:

python

bunch

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.

like image 652
joedborg Avatar asked Dec 01 '25 02:12

joedborg


2 Answers

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

b = Bunch.fromDict({'hello': {'world': 'foo'}})
b.hello.world
>>> 'foo'
like image 99
joedborg Avatar answered Dec 02 '25 17:12

joedborg


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'
like image 33
Mureinik Avatar answered Dec 02 '25 16:12

Mureinik