| 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 |
|
| 18 |
from typing import ( |
| 19 |
Optional, |
| 20 |
Self, |
| 21 |
) |
| 22 |
|
| 23 |
|
| 24 |
class ContextNode(): |
| 25 |
"""A class for defining nested objects. |
| 26 |
|
| 27 |
Attributes: |
| 28 |
name (str): |
| 29 |
The key identifier for this node. |
| 30 |
Nodes belonging to the same parent must have not have the same |
| 31 |
name. |
| 32 |
|
| 33 |
Examples: |
| 34 |
Define the tree: |
| 35 |
>>> with ContextNode('a') as a: |
| 36 |
... # create parent nodes using a context |
| 37 |
... # manager |
| 38 |
... with ContextNode('b') as b: |
| 39 |
... # create "leaf" nodes without |
| 40 |
... # a context manager |
| 41 |
... c = ContextNode('c') |
| 42 |
... d = ContextNode('d') |
| 43 |
|
| 44 |
The "key" for this node: |
| 45 |
>>> str(c) |
| 46 |
'c' |
| 47 |
>>> repr(c) |
| 48 |
'a/b/c' |
| 49 |
|
| 50 |
List ancestry: |
| 51 |
>>> list(c.parents()) |
| 52 |
[a/b, a] |
| 53 |
|
| 54 |
Iterate through children: |
| 55 |
>>> list(a) |
| 56 |
[a/b, a/d] |
| 57 |
|
| 58 |
Summarise the tree: |
| 59 |
>>> print(a.tree()) |
| 60 |
a |
| 61 |
b |
| 62 |
c |
| 63 |
d |
| 64 |
|
| 65 |
Node Terminology: |
| 66 |
Root/ |
| 67 |
Parent/ |
| 68 |
Leaf |
| 69 |
Leaf |
| 70 |
|
| 71 |
Class Attributes: |
| 72 |
ROOT_NAME_FMT (str): |
| 73 |
String representation for *root* nodes to be evaluated as a format |
| 74 |
string. Can use any of the instance attributes. |
| 75 |
ROOT_NAME_FMT (str): |
| 76 |
String representation for parent nodes. |
| 77 |
ROOT_NAME_FMT (str): |
| 78 |
String representation for leaf nodes. |
| 79 |
SEP (str): |
| 80 |
String to separate components in a nodes repr(). |
| 81 |
|
| 82 |
""" |
| 83 |
|
| 84 |
__slots__ = ('name', '_parent', '_children') |
| 85 |
|
| 86 |
ROOT_NAME_FMT = '{name}' |
| 87 |
NODE_NAME_FMT = '{name}' |
| 88 |
LEAF_NAME_FMT = '{name}' |
| 89 |
SEP = '/' |
| 90 |
|
| 91 |
DATA: dict = {} |
| 92 |
|
| 93 |
def __init__(self, name: str): |
| 94 |
self.name = name |
| 95 |
self._parent = None |
| 96 |
self._children = None |
| 97 |
self.DATA[self] = set(self.DATA) |
| 98 |
|
| 99 |
def __enter__(self) -> 'Self': |
| 100 |
return self |
| 101 |
|
| 102 |
def __exit__(self, *args): |
| 103 |
# list the nodes already present on this node |
| 104 |
older_siblings = self._children or {} |
| 105 |
# list the nodes which were created since we |
| 106 |
# __entered__ this node |
| 107 |
new_borns = { |
| 108 |
value.name: value |
| 109 |
for value in self.DATA |
| 110 |
if value is not self |
| 111 |
if value not in self.DATA.get(self, {}) |
| 112 |
} |
| 113 |
self._children = { |
| 114 |
**older_siblings, |
| 115 |
**new_borns |
| 116 |
} |
| 117 |
for child in new_borns.values(): |
| 118 |
# remove our children from self.DATA |
| 119 |
del self.DATA[child] |
| 120 |
# set our children to see us as their parent |
| 121 |
child._parent = self |
| 122 |
if len(self.DATA) == 1: |
| 123 |
# this is a root node, clean up after ourselves |
| 124 |
# self.DATA *should* be clean after each tree |
| 125 |
del self.DATA[self] |
| 126 |
|
| 127 |
def __iter__(self): |
| 128 |
if self._children: |
| 129 |
return iter(self._children.values()) |
| 130 |
return iter([]) |
| 131 |
|
| 132 |
def __contains__(self, name: str) -> bool: |
| 133 |
return name in self._children # type: ignore[operator] # TODO |
| 134 |
|
| 135 |
def __getitem__(self, name: str) -> 'Self': |
| 136 |
if self._children: |
| 137 |
return self._children.__getitem__(name) |
| 138 |
raise TypeError('This is not a leaf node') |
| 139 |
|
| 140 |
def get(self, *names: str) -> 'Self': |
| 141 |
"""Retrieve the node given by the list of names. |
| 142 |
|
| 143 |
Example: |
| 144 |
>>> with ContextNode('a') as a: |
| 145 |
... with ContextNode('b'): |
| 146 |
... c = ContextNode('c') |
| 147 |
>>> a.get('b', 'c') |
| 148 |
a/b/c |
| 149 |
|
| 150 |
>>> with ContextNode('a') as a: |
| 151 |
... with ContextNode('b'): |
| 152 |
... with ContextNode('__MANY__'): |
| 153 |
... c = ContextNode('c') |
| 154 |
>>> a.get('b', 'foo', 'c') |
| 155 |
a/b/__MANY__/c |
| 156 |
""" |
| 157 |
node = self |
| 158 |
for name in names: |
| 159 |
try: |
| 160 |
node = node[name] |
| 161 |
except KeyError as exc: |
| 162 |
if '__MANY__' not in node: |
| 163 |
raise exc |
| 164 |
node = node['__MANY__'] |
| 165 |
return node |
| 166 |
|
| 167 |
def __str__(self) -> str: |
| 168 |
if self.is_root(): |
| 169 |
fmt = self.ROOT_NAME_FMT |
| 170 |
elif not self.is_leaf(): |
| 171 |
fmt = self.NODE_NAME_FMT |
| 172 |
else: |
| 173 |
fmt = self.LEAF_NAME_FMT |
| 174 |
return fmt.format_map({ |
| 175 |
key: getattr(self, key) |
| 176 |
for key in self.__slots__ |
| 177 |
}) |
| 178 |
|
| 179 |
def __repr__(self) -> str: |
| 180 |
return self.SEP.join( |
| 181 |
[ |
| 182 |
str(node) |
| 183 |
for node in reversed(list(self.parents())) |
| 184 |
] + [ |
| 185 |
str(self) |
| 186 |
] |
| 187 |
) |
| 188 |
|
| 189 |
def is_root(self) -> bool: |
| 190 |
"""Return True if this is a root node.""" |
| 191 |
return self._parent is None |
| 192 |
|
| 193 |
def is_leaf(self) -> bool: |
| 194 |
"""Return True if this is a leaf node.""" |
| 195 |
return self._children is None |
| 196 |
|
| 197 |
def parents(self): |
| 198 |
"""Yield the linearised parents of this node. |
| 199 |
|
| 200 |
Yields: |
| 201 |
ContextNode |
| 202 |
|
| 203 |
Examples: |
| 204 |
>>> with ContextNode('a') as a: |
| 205 |
... with ContextNode('b') as b: |
| 206 |
... c = ContextNode('c') |
| 207 |
>>> c.parents().__next__() |
| 208 |
a/b |
| 209 |
>>> list(c.parents()) |
| 210 |
[a/b, a] |
| 211 |
|
| 212 |
""" |
| 213 |
pointer = self._parent |
| 214 |
while pointer: |
| 215 |
yield pointer |
| 216 |
pointer = pointer._parent |
| 217 |
|
| 218 |
def walk(self, depth: Optional[int] = None, _level: int = 0): |
| 219 |
"""Walk the context tree starting at this node. |
| 220 |
|
| 221 |
Args: |
| 222 |
depth: |
| 223 |
The max depth below the current node to yield. |
| 224 |
_level: |
| 225 |
(For recursive use, do not specify.) |
| 226 |
|
| 227 |
Yields: |
| 228 |
tuple - (level, node) |
| 229 |
|
| 230 |
level (int): |
| 231 |
The tree level measured from this node. |
| 232 |
node (ContextNode): |
| 233 |
The context node. |
| 234 |
|
| 235 |
Examples: |
| 236 |
>>> with ContextNode('a') as a: |
| 237 |
... with ContextNode('b') as b: |
| 238 |
... c = ContextNode('c') |
| 239 |
>>> list(a.walk()) |
| 240 |
[(0, a), (1, a/b), (2, a/b/c)] |
| 241 |
>>> list(c.walk()) |
| 242 |
[(0, a/b/c)] |
| 243 |
|
| 244 |
""" |
| 245 |
if depth is not None and _level >= depth: |
| 246 |
return |
| 247 |
if _level == 0: |
| 248 |
yield (0, self) |
| 249 |
for child in self: |
| 250 |
yield (_level + 1, child) |
| 251 |
yield from child.walk(depth=depth, _level=_level + 1) |
| 252 |
|
| 253 |
def tree(self): |
| 254 |
"""Return a string representation of the tree starting at this node. |
| 255 |
|
| 256 |
Returns: |
| 257 |
str |
| 258 |
|
| 259 |
Examples: |
| 260 |
>>> with ContextNode('a') as a: |
| 261 |
... with ContextNode('b') as b: |
| 262 |
... c = ContextNode('c') |
| 263 |
>>> print(a.tree()) |
| 264 |
a |
| 265 |
b |
| 266 |
c |
| 267 |
|
| 268 |
""" |
| 269 |
return '\n'.join(( |
| 270 |
f'{" " * level}{node}' |
| 271 |
for level, node in self.walk() |
| 272 |
)) |