File size: 16,150 Bytes
ab4488b |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 |
# -*- coding: utf-8 -*-
from anytree.iterators import PreOrderIter
from ..config import ASSERTIONS
from .exceptions import LoopError, TreeError
class LightNodeMixin:
"""
The :any:`LightNodeMixin` behaves identical to :any:`NodeMixin`, but uses `__slots__`.
There are some minor differences in the object behaviour.
See slots_ for any details.
.. _slots: https://docs.python.org/3/reference/datamodel.html#slots
The only tree relevant information is the `parent` attribute.
If `None` the :any:`LightNodeMixin` is root node.
If set to another node, the :any:`LightNodeMixin` becomes the child of it.
The `children` attribute can be used likewise.
If `None` the :any:`LightNodeMixin` has no children.
The `children` attribute can be set to any iterable of :any:`LightNodeMixin` instances.
These instances become children of the node.
>>> from anytree import LightNodeMixin, RenderTree
>>> class MyBaseClass(): # Just an example of a base class
... __slots__ = []
>>> class MyClass(MyBaseClass, LightNodeMixin): # Add Node feature
... __slots__ = ['name', 'length', 'width']
... def __init__(self, name, length, width, parent=None, children=None):
... super().__init__()
... self.name = name
... self.length = length
... self.width = width
... self.parent = parent
... if children:
... self.children = children
Construction via `parent`:
>>> my0 = MyClass('my0', 0, 0)
>>> my1 = MyClass('my1', 1, 0, parent=my0)
>>> my2 = MyClass('my2', 0, 2, parent=my0)
>>> for pre, _, node in RenderTree(my0):
... treestr = u"%s%s" % (pre, node.name)
... print(treestr.ljust(8), node.length, node.width)
my0 0 0
βββ my1 1 0
βββ my2 0 2
Construction via `children`:
>>> my0 = MyClass('my0', 0, 0, children=[
... MyClass('my1', 1, 0),
... MyClass('my2', 0, 2),
... ])
>>> for pre, _, node in RenderTree(my0):
... treestr = u"%s%s" % (pre, node.name)
... print(treestr.ljust(8), node.length, node.width)
my0 0 0
βββ my1 1 0
βββ my2 0 2
Both approaches can be mixed:
>>> my0 = MyClass('my0', 0, 0, children=[
... MyClass('my1', 1, 0),
... ])
>>> my2 = MyClass('my2', 0, 2, parent=my0)
>>> for pre, _, node in RenderTree(my0):
... treestr = u"%s%s" % (pre, node.name)
... print(treestr.ljust(8), node.length, node.width)
my0 0 0
βββ my1 1 0
βββ my2 0 2
"""
__slots__ = ["__parent", "__children"]
separator = "/"
@property
def parent(self):
"""
Parent Node.
On set, the node is detached from any previous parent node and attached
to the new node.
>>> from anytree import Node, RenderTree
>>> udo = Node("Udo")
>>> marc = Node("Marc")
>>> lian = Node("Lian", parent=marc)
>>> print(RenderTree(udo))
Node('/Udo')
>>> print(RenderTree(marc))
Node('/Marc')
βββ Node('/Marc/Lian')
**Attach**
>>> marc.parent = udo
>>> print(RenderTree(udo))
Node('/Udo')
βββ Node('/Udo/Marc')
βββ Node('/Udo/Marc/Lian')
**Detach**
To make a node to a root node, just set this attribute to `None`.
>>> marc.is_root
False
>>> marc.parent = None
>>> marc.is_root
True
"""
if hasattr(self, "_LightNodeMixin__parent"):
return self.__parent
return None
@parent.setter
def parent(self, value):
if hasattr(self, "_LightNodeMixin__parent"):
parent = self.__parent
else:
parent = None
if parent is not value:
self.__check_loop(value)
self.__detach(parent)
self.__attach(value)
def __check_loop(self, node):
if node is not None:
if node is self:
msg = "Cannot set parent. %r cannot be parent of itself."
raise LoopError(msg % (self,))
if any(child is self for child in node.iter_path_reverse()):
msg = "Cannot set parent. %r is parent of %r."
raise LoopError(msg % (self, node))
def __detach(self, parent):
# pylint: disable=W0212,W0238
if parent is not None:
self._pre_detach(parent)
parentchildren = parent.__children_or_empty
if ASSERTIONS: # pragma: no branch
assert any(child is self for child in parentchildren), "Tree is corrupt." # pragma: no cover
# ATOMIC START
parent.__children = [child for child in parentchildren if child is not self]
self.__parent = None
# ATOMIC END
self._post_detach(parent)
def __attach(self, parent):
# pylint: disable=W0212
if parent is not None:
self._pre_attach(parent)
parentchildren = parent.__children_or_empty
if ASSERTIONS: # pragma: no branch
assert not any(child is self for child in parentchildren), "Tree is corrupt." # pragma: no cover
# ATOMIC START
parentchildren.append(self)
self.__parent = parent
# ATOMIC END
self._post_attach(parent)
@property
def __children_or_empty(self):
if not hasattr(self, "_LightNodeMixin__children"):
self.__children = []
return self.__children
@property
def children(self):
"""
All child nodes.
>>> from anytree import Node
>>> n = Node("n")
>>> a = Node("a", parent=n)
>>> b = Node("b", parent=n)
>>> c = Node("c", parent=n)
>>> n.children
(Node('/n/a'), Node('/n/b'), Node('/n/c'))
Modifying the children attribute modifies the tree.
**Detach**
The children attribute can be updated by setting to an iterable.
>>> n.children = [a, b]
>>> n.children
(Node('/n/a'), Node('/n/b'))
Node `c` is removed from the tree.
In case of an existing reference, the node `c` does not vanish and is the root of its own tree.
>>> c
Node('/c')
**Attach**
>>> d = Node("d")
>>> d
Node('/d')
>>> n.children = [a, b, d]
>>> n.children
(Node('/n/a'), Node('/n/b'), Node('/n/d'))
>>> d
Node('/n/d')
**Duplicate**
A node can just be the children once. Duplicates cause a :any:`TreeError`:
>>> n.children = [a, b, d, a]
Traceback (most recent call last):
...
anytree.node.exceptions.TreeError: Cannot add node Node('/n/a') multiple times as child.
"""
return tuple(self.__children_or_empty)
@staticmethod
def __check_children(children):
seen = set()
for child in children:
childid = id(child)
if childid not in seen:
seen.add(childid)
else:
msg = "Cannot add node %r multiple times as child." % (child,)
raise TreeError(msg)
@children.setter
def children(self, children):
# convert iterable to tuple
children = tuple(children)
LightNodeMixin.__check_children(children)
# ATOMIC start
old_children = self.children
del self.children
try:
self._pre_attach_children(children)
for child in children:
child.parent = self
self._post_attach_children(children)
if ASSERTIONS: # pragma: no branch
assert len(self.children) == len(children)
except Exception:
self.children = old_children
raise
# ATOMIC end
@children.deleter
def children(self):
children = self.children
self._pre_detach_children(children)
for child in self.children:
child.parent = None
if ASSERTIONS: # pragma: no branch
assert len(self.children) == 0
self._post_detach_children(children)
def _pre_detach_children(self, children):
"""Method call before detaching `children`."""
def _post_detach_children(self, children):
"""Method call after detaching `children`."""
def _pre_attach_children(self, children):
"""Method call before attaching `children`."""
def _post_attach_children(self, children):
"""Method call after attaching `children`."""
@property
def path(self):
"""
Path from root node down to this `Node`.
>>> from anytree import Node
>>> udo = Node("Udo")
>>> marc = Node("Marc", parent=udo)
>>> lian = Node("Lian", parent=marc)
>>> udo.path
(Node('/Udo'),)
>>> marc.path
(Node('/Udo'), Node('/Udo/Marc'))
>>> lian.path
(Node('/Udo'), Node('/Udo/Marc'), Node('/Udo/Marc/Lian'))
"""
return self._path
def iter_path_reverse(self):
"""
Iterate up the tree from the current node to the root node.
>>> from anytree import Node
>>> udo = Node("Udo")
>>> marc = Node("Marc", parent=udo)
>>> lian = Node("Lian", parent=marc)
>>> for node in udo.iter_path_reverse():
... print(node)
Node('/Udo')
>>> for node in marc.iter_path_reverse():
... print(node)
Node('/Udo/Marc')
Node('/Udo')
>>> for node in lian.iter_path_reverse():
... print(node)
Node('/Udo/Marc/Lian')
Node('/Udo/Marc')
Node('/Udo')
"""
node = self
while node is not None:
yield node
node = node.parent
@property
def _path(self):
return tuple(reversed(list(self.iter_path_reverse())))
@property
def ancestors(self):
"""
All parent nodes and their parent nodes.
>>> from anytree import Node
>>> udo = Node("Udo")
>>> marc = Node("Marc", parent=udo)
>>> lian = Node("Lian", parent=marc)
>>> udo.ancestors
()
>>> marc.ancestors
(Node('/Udo'),)
>>> lian.ancestors
(Node('/Udo'), Node('/Udo/Marc'))
"""
if self.parent is None:
return tuple()
return self.parent.path
@property
def descendants(self):
"""
All child nodes and all their child nodes.
>>> from anytree import Node
>>> udo = Node("Udo")
>>> marc = Node("Marc", parent=udo)
>>> lian = Node("Lian", parent=marc)
>>> loui = Node("Loui", parent=marc)
>>> soe = Node("Soe", parent=lian)
>>> udo.descendants
(Node('/Udo/Marc'), Node('/Udo/Marc/Lian'), Node('/Udo/Marc/Lian/Soe'), Node('/Udo/Marc/Loui'))
>>> marc.descendants
(Node('/Udo/Marc/Lian'), Node('/Udo/Marc/Lian/Soe'), Node('/Udo/Marc/Loui'))
>>> lian.descendants
(Node('/Udo/Marc/Lian/Soe'),)
"""
return tuple(PreOrderIter(self))[1:]
@property
def root(self):
"""
Tree Root Node.
>>> from anytree import Node
>>> udo = Node("Udo")
>>> marc = Node("Marc", parent=udo)
>>> lian = Node("Lian", parent=marc)
>>> udo.root
Node('/Udo')
>>> marc.root
Node('/Udo')
>>> lian.root
Node('/Udo')
"""
node = self
while node.parent is not None:
node = node.parent
return node
@property
def siblings(self):
"""
Tuple of nodes with the same parent.
>>> from anytree import Node
>>> udo = Node("Udo")
>>> marc = Node("Marc", parent=udo)
>>> lian = Node("Lian", parent=marc)
>>> loui = Node("Loui", parent=marc)
>>> lazy = Node("Lazy", parent=marc)
>>> udo.siblings
()
>>> marc.siblings
()
>>> lian.siblings
(Node('/Udo/Marc/Loui'), Node('/Udo/Marc/Lazy'))
>>> loui.siblings
(Node('/Udo/Marc/Lian'), Node('/Udo/Marc/Lazy'))
"""
parent = self.parent
if parent is None:
return tuple()
return tuple(node for node in parent.children if node is not self)
@property
def leaves(self):
"""
Tuple of all leaf nodes.
>>> from anytree import Node
>>> udo = Node("Udo")
>>> marc = Node("Marc", parent=udo)
>>> lian = Node("Lian", parent=marc)
>>> loui = Node("Loui", parent=marc)
>>> lazy = Node("Lazy", parent=marc)
>>> udo.leaves
(Node('/Udo/Marc/Lian'), Node('/Udo/Marc/Loui'), Node('/Udo/Marc/Lazy'))
>>> marc.leaves
(Node('/Udo/Marc/Lian'), Node('/Udo/Marc/Loui'), Node('/Udo/Marc/Lazy'))
"""
return tuple(PreOrderIter(self, filter_=lambda node: node.is_leaf))
@property
def is_leaf(self):
"""
`Node` has no children (External Node).
>>> from anytree import Node
>>> udo = Node("Udo")
>>> marc = Node("Marc", parent=udo)
>>> lian = Node("Lian", parent=marc)
>>> udo.is_leaf
False
>>> marc.is_leaf
False
>>> lian.is_leaf
True
"""
return len(self.__children_or_empty) == 0
@property
def is_root(self):
"""
`Node` is tree root.
>>> from anytree import Node
>>> udo = Node("Udo")
>>> marc = Node("Marc", parent=udo)
>>> lian = Node("Lian", parent=marc)
>>> udo.is_root
True
>>> marc.is_root
False
>>> lian.is_root
False
"""
return self.parent is None
@property
def height(self):
"""
Number of edges on the longest path to a leaf `Node`.
>>> from anytree import Node
>>> udo = Node("Udo")
>>> marc = Node("Marc", parent=udo)
>>> lian = Node("Lian", parent=marc)
>>> udo.height
2
>>> marc.height
1
>>> lian.height
0
"""
children = self.__children_or_empty
if children:
return max(child.height for child in children) + 1
return 0
@property
def depth(self):
"""
Number of edges to the root `Node`.
>>> from anytree import Node
>>> udo = Node("Udo")
>>> marc = Node("Marc", parent=udo)
>>> lian = Node("Lian", parent=marc)
>>> udo.depth
0
>>> marc.depth
1
>>> lian.depth
2
"""
# count without storing the entire path
# pylint: disable=W0631
for depth, _ in enumerate(self.iter_path_reverse()):
continue
return depth
@property
def size(self):
"""
Tree size --- the number of nodes in tree starting at this node.
>>> from anytree import Node
>>> udo = Node("Udo")
>>> marc = Node("Marc", parent=udo)
>>> lian = Node("Lian", parent=marc)
>>> loui = Node("Loui", parent=marc)
>>> soe = Node("Soe", parent=lian)
>>> udo.size
5
>>> marc.size
4
>>> lian.size
2
>>> loui.size
1
"""
# count without storing the entire path
# pylint: disable=W0631
for size, _ in enumerate(PreOrderIter(self), 1):
continue
return size
def _pre_detach(self, parent):
"""Method call before detaching from `parent`."""
def _post_detach(self, parent):
"""Method call after detaching from `parent`."""
def _pre_attach(self, parent):
"""Method call before attaching to `parent`."""
def _post_attach(self, parent):
"""Method call after attaching to `parent`."""
|