| 1 |
# THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE. |
| 2 |
# Copyright (C) NIWA & British Crown (Met Office) & Contributors. |
| 3 |
# |
| 4 |
# This program is free software: you can redistribute it and/or modify |
| 5 |
# it under the terms of the GNU General Public License as published by |
| 6 |
# the Free Software Foundation, either version 3 of the License, or |
| 7 |
# (at your option) any later version. |
| 8 |
# |
| 9 |
# This program is distributed in the hope that it will be useful, |
| 10 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 |
# GNU General Public License for more details. |
| 13 |
# |
| 14 |
# You should have received a copy of the GNU General Public License |
| 15 |
# along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 16 |
|
| 17 |
"""Ordered Dictionary data structure used extensively in cylc.""" |
| 18 |
|
| 19 |
|
| 20 |
from collections import OrderedDict |
| 21 |
|
| 22 |
|
| 23 |
class OrderedDictWithDefaults(OrderedDict): |
| 24 |
|
| 25 |
"""Subclass to provide defaults fetching capability.""" |
| 26 |
|
| 27 |
# Note that defining a '__missing__' method would work for foo[key], |
| 28 |
# but doesn't for foo.get(key). |
| 29 |
|
| 30 |
def __init__(self, *args, **kwargs): |
| 31 |
"""Allow a defaults argument.""" |
| 32 |
self._allow_contains_default = True |
| 33 |
super().__init__(*args, **kwargs) |
| 34 |
|
| 35 |
def __getitem__(self, key): |
| 36 |
# Override to look in our special defaults attribute, if it exists. |
| 37 |
try: |
| 38 |
return OrderedDict.__getitem__(self, key) |
| 39 |
except KeyError: |
| 40 |
if hasattr(self, 'defaults_'): |
| 41 |
return self.defaults_[key] |
| 42 |
raise |
| 43 |
|
| 44 |
def __setitem__(self, *args, **kwargs): |
| 45 |
# Make sure that we don't set the default value! |
| 46 |
self._allow_contains_default = False |
| 47 |
return_value = OrderedDict.__setitem__(self, *args, **kwargs) |
| 48 |
self._allow_contains_default = True |
| 49 |
return return_value |
| 50 |
|
| 51 |
def keys(self): |
| 52 |
"""Include the default keys, after the list of actually-set ones.""" |
| 53 |
keys = list(self) |
| 54 |
for key in getattr(self, 'defaults_', []): |
| 55 |
if key not in keys: |
| 56 |
keys.append(key) |
| 57 |
return keys |
| 58 |
|
| 59 |
def values(self): |
| 60 |
"""Return a list of values, including default ones.""" |
| 61 |
return [self[key] for key in self.keys()] |
| 62 |
|
| 63 |
def items(self): |
| 64 |
"""Return key-value pairs, including default ones.""" |
| 65 |
return [(key, self[key]) for key in self.keys()] |
| 66 |
|
| 67 |
def iterkeys(self): |
| 68 |
"""Include default keys""" |
| 69 |
yield from OrderedDict.keys(self) |
| 70 |
for key in getattr(self, 'defaults_', []): |
| 71 |
if not OrderedDict.__contains__(self, key): |
| 72 |
yield key |
| 73 |
|
| 74 |
def itervalues(self): |
| 75 |
"""Include default values.""" |
| 76 |
for k in self.keys(): |
| 77 |
yield self[k] |
| 78 |
|
| 79 |
def iteritems(self): |
| 80 |
"""Include default key-value pairs.""" |
| 81 |
for k in self.keys(): |
| 82 |
yield (k, self[k]) |
| 83 |
|
| 84 |
def __contains__(self, key): |
| 85 |
if ( |
| 86 |
self._allow_contains_default |
| 87 |
and key in getattr(self, "defaults_", {}) |
| 88 |
): |
| 89 |
return True |
| 90 |
return OrderedDict.__contains__(self, key) |
| 91 |
|
| 92 |
def __bool__(self): |
| 93 |
"""Include any default keys in the nonzero calculation.""" |
| 94 |
return bool(list(self.keys())) |
| 95 |
|
| 96 |
def prepend(self, key, value): |
| 97 |
"""Prepend new item in the ordered dict.""" |
| 98 |
# https://stackoverflow.com/questions/16664874/ |
| 99 |
# how-can-i-add-an-element-at-the-top-of-an-ordereddict-in-python |
| 100 |
self[key] = value |
| 101 |
self.move_to_end(key, last=False) |
| 102 |
|
| 103 |
|
| 104 |
class DictTree: |
| 105 |
"""An object providing a single point of access to a tree of dicts. |
| 106 |
|
| 107 |
* Allows easy extraction of values from a collection of dictionaries. |
| 108 |
* Values from dictionaries earlier in the list will take priority over |
| 109 |
values from dictionaries later in the list. |
| 110 |
* If the dict objects provided provide a custom `get` interface this |
| 111 |
will take priority over the `__getitem__` interface. |
| 112 |
|
| 113 |
Args: |
| 114 |
tree (list): |
| 115 |
A list of dict-type objects. |
| 116 |
|
| 117 |
Examples: |
| 118 |
Regular usage: |
| 119 |
>>> tree = DictTree( |
| 120 |
... {'a': 1, 'b': 2}, |
| 121 |
... {'b': 3, 'c': 4} |
| 122 |
... ) |
| 123 |
>>> tree['a'] |
| 124 |
1 |
| 125 |
>>> tree['b'] # items from earlier entries are preferred |
| 126 |
2 |
| 127 |
>>> tree['c'] |
| 128 |
4 |
| 129 |
>>> tree['d'] |
| 130 |
Traceback (most recent call last): |
| 131 |
KeyError: 'd' |
| 132 |
|
| 133 |
Quirk, None values result in KeyErrors: |
| 134 |
>>> tree = DictTree({'a': None}) |
| 135 |
>>> tree['a'] |
| 136 |
Traceback (most recent call last): |
| 137 |
KeyError: 'a' |
| 138 |
|
| 139 |
""" |
| 140 |
|
| 141 |
def __init__(self, *tree): |
| 142 |
self._tree = tree |
| 143 |
|
| 144 |
def __getitem__(self, key): |
| 145 |
values = [] |
| 146 |
defaults = [] |
| 147 |
for branch in self._tree: |
| 148 |
# priority goes to the `get` method |
| 149 |
value = branch.get(key) |
| 150 |
if value is not None: |
| 151 |
values.append(value) |
| 152 |
defaults.append(None) |
| 153 |
else: |
| 154 |
try: |
| 155 |
# then falls back to the `__getitem__` method |
| 156 |
defaults.append(branch[key]) |
| 157 |
values.append(None) |
| 158 |
except KeyError: |
| 159 |
# okay, this key really isn't present here |
| 160 |
values.append(None) |
| 161 |
defaults.append(None) |
| 162 |
|
| 163 |
# handle nested dictionaries |
| 164 |
if any((isinstance(item, dict) for item in values + defaults)): |
| 165 |
return DictTree(*( |
| 166 |
item |
| 167 |
for item in values |
| 168 |
if item is not None |
| 169 |
)) |
| 170 |
|
| 171 |
# handle non-existent keys |
| 172 |
if all((item is None for item in values + defaults)): |
| 173 |
raise KeyError(key) |
| 174 |
|
| 175 |
# return first value or default encountered |
| 176 |
return next(( |
| 177 |
item |
| 178 |
for item in values + defaults |
| 179 |
if item is not None |
| 180 |
)) |
| 181 |
|
| 182 |
def __eq__(self, other): |
| 183 |
if not isinstance(other, DictTree): |
| 184 |
return False |
| 185 |
return self._tree == other._tree |
| 186 |
|
| 187 |
def __iter__(self): |
| 188 |
def inner(tree): |
| 189 |
# yield keys from all branches (but only once) |
| 190 |
yield from { |
| 191 |
key |
| 192 |
for branch in tree |
| 193 |
for key in branch |
| 194 |
} |
| 195 |
return inner(self._tree) |
| 196 |
|
| 197 |
def get(self, key, default=None): |
| 198 |
"""Get an item from this tree or return `default` if not present. |
| 199 |
|
| 200 |
Note: |
| 201 |
Behaviour purposefully differs from OrderedDictWithDefaults, |
| 202 |
this `get` method *will* return default values if present. |
| 203 |
|
| 204 |
""" |
| 205 |
try: |
| 206 |
return self[key] |
| 207 |
except KeyError: |
| 208 |
return default |