• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2015 gRPC authors.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#     http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14"""Allows dot-accessible dictionaries."""
15
16
17class Bunch(dict):
18
19    def __init__(self, d):
20        dict.__init__(self, d)
21        self.__dict__.update(d)
22
23
24# Converts any kind of variable to a Bunch
25def to_bunch(var):
26    if isinstance(var, list):
27        return [to_bunch(i) for i in var]
28    if isinstance(var, dict):
29        ret = {}
30        for k, v in var.items():
31            if isinstance(v, (list, dict)):
32                v = to_bunch(v)
33            ret[k] = v
34        return Bunch(ret)
35    else:
36        return var
37
38
39# Merges JSON 'add' into JSON 'dst'
40def merge_json(dst, add):
41    if isinstance(dst, dict) and isinstance(add, dict):
42        for k, v in add.items():
43            if k in dst:
44                if k == '#': continue
45                merge_json(dst[k], v)
46            else:
47                dst[k] = v
48    elif isinstance(dst, list) and isinstance(add, list):
49        dst.extend(add)
50    else:
51        raise Exception(
52            'Tried to merge incompatible objects %s %s\n\n%r\n\n%r' %
53            (type(dst).__name__, type(add).__name__, dst, add))
54