| Conditions | 9 |
| Total Lines | 52 |
| Code Lines | 16 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 0 | ||
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
| 1 | """ |
||
| 68 | def recursive_merge_dicts(base_config, extra_config): |
||
| 69 | """ |
||
| 70 | recursively merge two dictionaries. |
||
| 71 | Entries in extra_config override entries in base_config. The built-in |
||
| 72 | update function cannot be used for hierarchical dicts. |
||
| 73 | |||
| 74 | Also for the case when there is a list of dicts involved, one has to be |
||
| 75 | more careful. The extra_config may have longer list of dicts as compared |
||
| 76 | with the base_config, in which case, the extra items are simply added to |
||
| 77 | the merged final list. |
||
| 78 | |||
| 79 | Combined here are 2 options from SO. |
||
| 80 | |||
| 81 | See: |
||
| 82 | http://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth/3233356#3233356 |
||
| 83 | and also |
||
| 84 | https://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth/18394648#18394648 |
||
| 85 | |||
| 86 | Parameters |
||
| 87 | ---------- |
||
| 88 | base_config : dict |
||
| 89 | dictionary to be merged |
||
| 90 | extra_config : dict |
||
| 91 | dictionary to be merged |
||
| 92 | Returns |
||
| 93 | ------- |
||
| 94 | final_config : dict |
||
| 95 | merged dict |
||
| 96 | """ |
||
| 97 | final_config = base_config.copy() |
||
| 98 | |||
| 99 | for key, value in extra_config.items(): |
||
| 100 | if key in final_config and isinstance(final_config[key], list): |
||
| 101 | new_config = [] |
||
| 102 | |||
| 103 | for key_, value_ in zip(final_config[key], value, strict=False): |
||
| 104 | key_ = recursive_merge_dicts(key_ or {}, value_) |
||
| 105 | new_config.append(key_) |
||
| 106 | |||
| 107 | # For example moving from a smaller list of model parameters to a |
||
| 108 | # longer list. |
||
| 109 | if len(final_config[key]) < len(extra_config[key]): |
||
| 110 | for value_ in value[len(final_config[key]) :]: |
||
| 111 | new_config.append(value_) |
||
| 112 | final_config[key] = new_config |
||
| 113 | |||
| 114 | elif key in final_config and isinstance(final_config[key], dict): |
||
| 115 | final_config[key] = recursive_merge_dicts(final_config.get(key) or {}, value) |
||
| 116 | else: |
||
| 117 | final_config[key] = value |
||
| 118 | |||
| 119 | return final_config |
||
| 120 | |||
| 155 |