symlinknodemixin.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. # -*- coding: utf-8 -*-
  2. from .nodemixin import NodeMixin
  3. class SymlinkNodeMixin(NodeMixin):
  4. u"""
  5. The :any:`SymlinkNodeMixin` class extends any Python class to a symbolic link to a tree node.
  6. The class **MUST** have a `target` attribute refering to another tree node.
  7. The :any:`SymlinkNodeMixin` class has its own parent and its own child nodes.
  8. All other attribute accesses are just forwarded to the target node.
  9. A minimal implementation looks like (see :any:`SymlinkNode` for a full implemenation):
  10. >>> from anytree import SymlinkNodeMixin, Node, RenderTree
  11. >>> class SymlinkNode(SymlinkNodeMixin):
  12. ... def __init__(self, target, parent=None, children=None):
  13. ... self.target = target
  14. ... self.parent = parent
  15. ... if children:
  16. ... self.children = children
  17. ... def __repr__(self):
  18. ... return "SymlinkNode(%r)" % (self.target)
  19. >>> root = Node("root")
  20. >>> s1 = Node("sub1", parent=root)
  21. >>> l = SymlinkNode(s1, parent=root)
  22. >>> l0 = Node("l0", parent=l)
  23. >>> print(RenderTree(root))
  24. Node('/root')
  25. ├── Node('/root/sub1')
  26. └── SymlinkNode(Node('/root/sub1'))
  27. └── Node('/root/sub1/l0')
  28. Any modifications on the target node are also available on the linked node and vice-versa:
  29. >>> s1.foo = 4
  30. >>> s1.foo
  31. 4
  32. >>> l.foo
  33. 4
  34. >>> l.foo = 9
  35. >>> s1.foo
  36. 9
  37. >>> l.foo
  38. 9
  39. """
  40. def __getattr__(self, name):
  41. if name in ('_NodeMixin__parent', '_NodeMixin__children'):
  42. return super(SymlinkNodeMixin, self).__getattr__(name)
  43. else:
  44. return getattr(self.target, name)
  45. def __setattr__(self, name, value):
  46. if name in ('_NodeMixin__parent', '_NodeMixin__children', 'parent', 'children', 'target'):
  47. super(SymlinkNodeMixin, self).__setattr__(name, value)
  48. else:
  49. return setattr(self.target, name, value)