Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/traitlets/utils/nested_update.py: 17%

12 statements  

« prev     ^ index     » next       coverage.py v7.3.3, created at 2023-12-15 06:13 +0000

1# Copyright (c) IPython Development Team. 

2# Distributed under the terms of the Modified BSD License. 

3from typing import Any, Dict 

4 

5 

6def nested_update(this: Dict[Any, Any], that: Dict[Any, Any]) -> Dict[Any, Any]: 

7 """Merge two nested dictionaries. 

8 

9 Effectively a recursive ``dict.update``. 

10 

11 Examples 

12 -------- 

13 Merge two flat dictionaries: 

14 >>> nested_update( 

15 ... {'a': 1, 'b': 2}, 

16 ... {'b': 3, 'c': 4} 

17 ... ) 

18 {'a': 1, 'b': 3, 'c': 4} 

19 

20 Merge two nested dictionaries: 

21 >>> nested_update( 

22 ... {'x': {'a': 1, 'b': 2}, 'y': 5, 'z': 6}, 

23 ... {'x': {'b': 3, 'c': 4}, 'z': 7, '0': 8}, 

24 ... ) 

25 {'x': {'a': 1, 'b': 3, 'c': 4}, 'y': 5, 'z': 7, '0': 8} 

26 

27 """ 

28 for key, value in this.items(): 

29 if isinstance(value, dict): 

30 if key in that and isinstance(that[key], dict): 

31 nested_update(this[key], that[key]) 

32 elif key in that: 

33 this[key] = that[key] 

34 

35 for key, value in that.items(): 

36 if key not in this: 

37 this[key] = value 

38 

39 return this