blob: f3bfc81102c96d2c4143368223af9fe28b2369d6 [file] [log] [blame]
Jan Tattermusch7897ae92017-06-07 22:57:36 +02001# Copyright 2015 gRPC authors.
Craig Tillerc2c79212015-02-16 12:00:01 -08002#
Jan Tattermusch7897ae92017-06-07 22:57:36 +02003# 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
Craig Tillerc2c79212015-02-16 12:00:01 -08006#
Jan Tattermusch7897ae92017-06-07 22:57:36 +02007# http://www.apache.org/licenses/LICENSE-2.0
Craig Tillerc2c79212015-02-16 12:00:01 -08008#
Jan Tattermusch7897ae92017-06-07 22:57:36 +02009# 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.
Nicolas Nobleddef2462015-01-06 18:08:25 -080014"""Allows dot-accessible dictionaries."""
15
16
17class Bunch(dict):
18
ncteisen26d70b12017-12-11 16:40:56 -080019 def __init__(self, d):
20 dict.__init__(self, d)
21 self.__dict__.update(d)
Nicolas Nobleddef2462015-01-06 18:08:25 -080022
23
24# Converts any kind of variable to a Bunch
25def to_bunch(var):
ncteisen26d70b12017-12-11 16:40:56 -080026 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
Nicolas Nobleddef2462015-01-06 18:08:25 -080037
38
39# Merges JSON 'add' into JSON 'dst'
40def merge_json(dst, add):
ncteisen26d70b12017-12-11 16:40:56 -080041 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:
Mehrdad Afshari87cd9942018-01-02 14:40:00 -080051 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))