Debian Codegraph @

gavo/utils/autonode.py

raw
1 """
2 Autonodes are stripped-down versions of the full DaCHS structures.
3
4 The idea is to have "managed attributes light" with automatic
5 constructors. The Autonodes are used when building something like abstract
6 syntax trees in STC or ADQL.
7 """
8
9 #c Copyright 2008-2025, the GAVO project <[email protected]>
10 #c
11 #c This program is free software, covered by the GNU GPL. See the
12 #c COPYING file in the source distribution.
13
14
15 import itertools
16
17
18 from gavo.utils.dachstypes import Any, Dict, List, Tuple
19
20
21 class AutoNodeType(type):
22 """A metaclass for AutoNodes.
23
24 The idea here is to define children in a class definition and make sure they
25 are actually present.
26
27 AutoNodes are supposed to be immutable; the are defined during construction.
28 Currently, nothing keeps you from changing them afterwards, but that may
29 change.
30
31 The classes' constructor is defined to accept all attributes as arguments
32 (you probably want to use keyword arguments here). It is the constructor
33 that sets up the attributes, so AutoNodes must not have an __init__ method.
34 However, they may define a method _setupNode that is called just before the
35 artificial constructor returns.
36
37 To define the attributes of the class, add _a_<attname> attributes
38 giving a default to the class. The default should normally be either
39 None for 1:1 or 1:0 relations or an empty tuple for 1:n relations.
40 The defaults must return a repr that constructs them, since we create
41 a source fragment.
42 """
43 def __init__(cls, name: str, bases: Tuple[type, ...], dict: Dict):
44 cls._collectAttributes()
45 cls._buildConstructor()
46
47 def _collectAttributes(cls) -> None:
48 cls._nodeAttrs: List[Tuple[str, Any]] = []
49 for name in dir(cls):
50 if name.startswith("_a_"):
51 cls._nodeAttrs.append((name[3:], getattr(cls, name)))
52
53 def _buildConstructor(cls) -> None:
54 argList, codeLines = ["self"], []
55 for argName, argDefault in cls._nodeAttrs:
56 argList.append("%s=%s"%(argName, repr(argDefault)))
57 codeLines.append(" self.%s = %s"%(argName, argName))
58 codeLines.append(" self._setupNode()\n")
59 codeLines.insert(0, "def constructor(%s):"%(", ".join(argList)))
60 ns: Dict[str, Any] = {}
61 exec("\n".join(codeLines), ns)
62 cls.__init__ = ns["constructor"] # type: ignore
63
64
65 class AutoNode(object, metaclass=AutoNodeType):
66 """A node in a tree with automatic attributes.
67
68 AutoNodes are explained in AutoNode's metaclass, AutoNodeType.
69
70 A noteworthy method is change -- pass in new attribute values
71 to create a new instance with the original attribute values except
72 for those passed to change. This will only work if all non-autoattribute
73 attributes of the class are set in _setupNode.
74 """
75
76 def _setupNodeNext(self, cls):
77 try:
78 pc = super(cls, self)._setupNode
79 except AttributeError:
80 pass
81 else:
82 pc()
83
84 def _setupNode(self):
85 self._setupNodeNext(AutoNode)
86
87 def __repr__(self):
88 return "<%s %s>"%(self.__class__.__name__, " ".join(
89 "%s=%s"%(name, repr(val))
90 for name, val in self.iterAttributes(skipEmpty=True)))
91
92 def change(self, **kwargs) -> 'AutoNode':
93 """returns a shallow copy of self with constructor arguments in kwargs
94 changed.
95 """
96 if not kwargs:
97 return self
98 consArgs = dict(self.iterAttributes())
99 consArgs.update(kwargs)
100 return self.__class__(**consArgs)
101
102 @classmethod
103 def cloneFrom(cls, other, **kwargs) -> 'AutoNode':
104 """returns a shallow clone of other.
105
106 other should be of the same class or a superclass.
107 """
108 consArgs = dict(other.iterAttributes())
109 consArgs.update(kwargs)
110 return cls(**consArgs)
111
112 def iterAttributes(self, skipEmpty: bool=False):
113 """yields pairs of attributeName, attributeValue for this node.
114 """
115 for name, _ in self._nodeAttrs: # type: ignore
116 val = getattr(self, name)
117 if skipEmpty and not val:
118 continue
119 yield name, val
120
121 def iterChildren(self, skipEmpty: bool=False):
122 for name, val in self.iterAttributes(skipEmpty):
123 if isinstance(val, (list, tuple)):
124 for c in val:
125 yield name, c
126 else:
127 yield name, val
128
129 def iterNodeChildren(self):
130 """yields pairs of attributeName, attributeValue for this node.
131
132 This will look into sequences, so multiple occurrences of an
133 attributeName are possible. Only nodes are returned.
134 """
135 for name, val in self.iterChildren(skipEmpty=True):
136 if isinstance(val, AutoNode) and val is not self:
137 yield val
138
139 def iterNodes(self):
140 """iterates the tree preorder.
141
142 Only AutoNodes are returned, not python values.
143 """
144 childIterators = [c.iterNodes() for c in self.iterNodeChildren()]
145 return itertools.chain((self,), *childIterators)