Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

# encoding: utf-8 

from __future__ import print_function, division, absolute_import 

 

 

class Bunch(dict): 

 

"""Bunch decorates a dict with attributes for accessing the string keys:: 

 

d = {"a": 3} 

x = Bunch(d) 

assert x.a == 3 

x.c = 7 

 

may be nested: 

 

d = {"a": 3, b: {"c": 4}} 

x = Bunch(d) 

assert x.b.c == 4 

""" 

 

def __init__(self, dict_): 

super(Bunch, self).__init__(dict_) 

for name, value in dict_.items(): 

if isinstance(value, dict): 

setattr(self, name, Bunch(value)) 

if isinstance(value, (list, tuple)): 

new_value = [] 

for item in value: 

if isinstance(item, dict) and not isinstance(item, Bunch): 

item = Bunch(item) 

new_value.append(item) 

if isinstance(value, tuple): 

new_value = tuple(new_value) 

setattr(self, name, new_value) 

 

def __setattr__(self, name, value): 

self[name] = value 

 

def __delattr__(self, name): 

del self[name] 

 

__getattr__ = dict.__getitem__ 

 

def copy(self): 

return Bunch(dict.copy(self))