Debian Codegraph @

gavo/base/attrdef.py

raw
1 """
2 Attribute definitions for structures.
3
4 These are objects having at least the following attributes and methods:
5
6 - name -- will become the attribute name on the embedding class
7 - parseName -- the name of the XML/event element they can parse. This
8 usually is identical to name, but may differ for compound attributes
9 - default -- may be Undefined, otherwise a valid value of the
10 expected type
11 - description -- for user documentation
12 - typeDesc -- describing the content; this is usually a class
13 attribute and intended for user documentation
14 - before -- the name of another attribute the attribute should precede
15 in XML serializations. It is not an error to refer to an attribute
16 that does not exist.
17 - feedObject(instance, ob) -> None -- adds ob to instance's attribute value.
18 This will usually just result in setting the attribute; for compound
19 attributes, this may instead append to a list, add to a set, etc.
20 - getCopy(instance, newParent, ctx) -> value -- returns the python value
21 of the attribute in instance, copying mutable values (deeply) in the
22 process.
23 - iterParentMethods() -> iter((name, value)) -- iterates over methods
24 to be inserted into the parent class.
25 - makeUserDoc() -> returns some RST-valid string describing what the object
26 is about (or None, in which case the attribute is hidden in the
27 documentation).
28
29 AtomicAttributes, defined as those that are parsed from a unicode literal,
30 add methods
31
32 - feed(ctx, instance, literal) -> None -- arranges for literal to be parsed
33 and passed to feedObject. ctx is a parse context. The built-in method
34 does not expect anything from this object, but structure has a default
35 implementation containing an idmap and a property registry.
36 - parse(self, value) -> anything -- returns a python value for the
37 unicode literal value
38 - unparse(self, value) -> unicode -- returns a unicode object representing
39 value and parseable by parse to that value.
40
41 Attributes can have aliases; they are always called in XML whatever their name
42 is. However, sometimes that's a bit odd; consider an list-valied attribute
43 ``groups``; an item from it should certainly be called ``group`` on input. For
44 situations like that, you can furnish attributes with a list of strings in
45 ``aliases``. Any alias, as well as the original name, is then legal
46 on input (and for attribute access, too, but don't rely on that). I
47 am considering whether to add some code to make the attribute name
48 itself unavailable as input names when there are aliases, but that's
49 probably trickier than it's worth.
50
51 This is not enough for complex attributes. More on those in the
52 base.complexattrs module.
53
54 AttributeDefs *may* have a validate(instance) method. Structure instances
55 will call them when they are done building. They should raise
56 LiteralParseErrors if it turns out a value that looked right is not after
57 all (in a way, they could catch validity rather than well-formedness violations,
58 but I don't think this distinction is necessary here).
59
60 See structure on how to use all these.
61 """
62
63 #c Copyright 2008-2025, the GAVO project <[email protected]>
64 #c
65 #c This program is free software, covered by the GNU GPL. See the
66 #c COPYING file in the source distribution.
67
68
69 import os
70 import re
71
72 from gavo import utils
73 from gavo.utils import Undefined
74 from gavo.base import literals
75 from gavo.base.common import LiteralParseError, NotGiven
76
77
78 from gavo.utils.dachstypes import (
79 Any, Callable, ClassVar, Dict, Iterable, Iterator, List, Optional, Set,
80 Structure, StructParseContext, Tuple, Union)
81
82 class Recursive:
83 """a sentinel class for attributes embedding structures to signify
84 they embed the structure embedding them.
85 """
86 name_ = "RECURSIVE"
87
88
89 class Computed:
90 """A sentinel class for computed (property) defaults.
91
92 Use this to construct AttributeDefs with defaults that are properties
93 to inhibit assigning to them. This should only be required in calls
94 of the superclass's init.
95 """
96
97
98 # Values for which no special stringification for docs is attempted
99 _NULL_LIKE = set([None, Undefined, NotGiven])
100 _NullLikeType = Union[None, utils.NotGivenType, utils.UndefinedType]
101
102
103 class AttributeDef:
104 """The base class for all attribute definitions.
105
106 See the module docstring for general information.
107
108 The data attribute names have all an underscore added to avoid name
109 clashes -- structures should have about the same attributes and may
110 want to have managed attributes called name or description.
111
112 When constructing AttributeDefs, you should only use keyword
113 arguments, except for name (the first argument).
114
115 Note that an AttributeDef might be embedded by many instances. So,
116 you must *never* store any instance data in an AttributeDef (unless
117 it's really a singleton, of course).
118 """
119
120 typeDesc_: ClassVar = "unspecified, invalid"
121 # A name into gavo.utils.dachstypes for what values can be assigned
122 # here (we probably should be smart here an add "Optional" as per
123 # default?)
124 typingType_: ClassVar = "Any"
125
126 def __init__(self,
127 name: str,
128 default: Any = None,
129 description: str = "Undocumented",
130 copyable: bool = False,
131 aliases: Iterable[str] = (),
132 callbacks: Optional[List[str]] = None,
133 before: Optional[str] = None) -> None:
134 self.name_, self.description_ = name, description
135 self.copyable = copyable
136 self.aliases = aliases
137 self.callbacks = callbacks
138 self.before = before
139 if default is not Computed:
140 self.default_ = default
141
142 def iterParentMethods(self
143 ) -> Iterator[Tuple[str, Union[Callable, property]]]:
144 """returns an iterator over (name, method) pairs that should be
145 inserted in the parent class.
146 """
147 return iter([])
148
149 def doCallbacks(self, instance: Structure, value: Any) -> None:
150 """should be called after feedObject has done its work.
151 """
152 if self.callbacks:
153 for cn in self.callbacks:
154 getattr(instance, cn)(value)
155
156 def feedObject(self, instance: Structure, value: Any): # pragma: no cover
157 raise NotImplementedError("%s doesn't implement feeding objects"%
158 self.__class__.__name__)
159
160 def feed(self, ctx, instance: Structure, value: Any): # pragma: no cover
161 raise NotImplementedError("%s doesn't implement feeding literals"%
162 self.__class__.__name__)
163
164 def getCopy(self, # pragma: no cover
165 instance: Structure,
166 newParent: Structure,
167 ctx: StructParseContext) -> Any:
168 raise NotImplementedError("%s cannot be copied."%
169 self.__class__.__name__)
170
171 def makeUserDoc(self) -> Optional[str]:
172 return "**%s** (%s; defaults to %s) -- %s"%(
173 self.name_, self.typeDesc_, repr(self.default_), self.description_)
174
175
176 class AtomicAttribute(AttributeDef):
177 """A base class for attributes than can be immediately parsed
178 and unparsed from strings.
179
180 They need to provide a parse method taking a unicode object and
181 returning a value of the proper type, and an unparse method taking
182 a value of the proper type and returning a unicode string suitable
183 for parse.
184
185 Note that you can, of course, assign to the attribute directly.
186 If you assign crap, the unparse method is explicitly allowed
187 to bomb in random ways; it just has to be guaranteed to work
188 for values coming from parse (i.e.: user input is checked,
189 programmatic input can blow up the thing; I consider this
190 pythonesque :-).
191 """
192 def parse(self, value: str) -> Any: # pragma: no cover
193 """returns a typed python value for the string representation value.
194
195 value can be expected to be a unicode string.
196 """
197 raise NotImplementedError("%s does not define a parse method"%
198 self.__class__.__name__)
199
200 def unparse(self, value: Any) -> Optional[str]: # pragma: no cover
201 """returns a typed python value for the string representation value.
202
203 value can be expected to be a unicode string.
204 """
205 raise NotImplementedError("%s does not define an unparse method"%
206 self.__class__.__name__)
207
208 def feed(self,
209 ctx: StructParseContext, instance: Structure, value: str) -> None:
210 self.feedObject(instance, self.parse(value))
211
212 def feedObject(self, instance: Structure, value: Any) -> None:
213 setattr(instance, self.name_, value)
214 self.doCallbacks(instance, value)
215
216 def getCopy(self,
217 instance: Structure,
218 newParent: Structure,
219 ctx: Optional[StructParseContext]) -> Any:
220 # We assume atoms are immutable here
221 return getattr(instance, self.name_)
222
223 def makeUserDoc(self) -> Optional[str]:
224 default = self.default_
225 try:
226 if default not in _NULL_LIKE:
227 default = self.unparse(default)
228 except TypeError: # unhashable defaults can be unparsed
229 default = self.unparse(default)
230 return "**%s** (%s; defaults to %s) -- %s"%(
231 self.name_, self.typeDesc_, repr(default), self.description_)
232
233
234 class RawAttribute(AtomicAttribute):
235 """An attribute definition that does no parsing at all.
236
237 This is only useful in "internal" structures that never get
238 serialized or deserialized.
239 """
240 def parse(self, value: str) -> Any:
241 return value
242
243 def unparse(self, value: Any) -> Any: #type: ignore
244 return value
245
246
247 class PostprocessedTextAttribute(AtomicAttribute):
248 """An abstract base for attributes that may need to do some
249 text processing.
250 """
251 def __init__(self, name: str, **kwargs: Any) -> None:
252 self.nullLiteral = kwargs.pop("null", "__NULL__")
253 self.strip = kwargs.pop("strip", False)
254 self.expand = kwargs.pop("expand", False)
255 AtomicAttribute.__init__(self, name, **kwargs)
256
257 def parse(self, value: Optional[str]) -> Any:
258 if isinstance(value, bytes):
259 value = value.decode("utf-8")
260
261 if value==self.nullLiteral:
262 return None
263 if self.strip and value is not None:
264 value = value.strip()
265 return value
266
267 def feed(self,
268 ctx: StructParseContext,
269 instance: Structure,
270 value: str) -> None:
271 # the type ignore here is because not all structs can expand
272 # macros, and it's too hard for me to explain to mypy which are.
273 if isinstance(value, str) and self.expand and "\\" in value:
274 value = instance.expand(value) # type: ignore
275 self.feedObject(instance, self.parse(value))
276
277
278 class UnicodeAttribute(PostprocessedTextAttribute):
279 """An attribute definition for an item containing a string.
280
281 This will decode bytes passed in assuming they're utf-8 and fail
282 if they're not. Unparsing will not bring them back to bytes.
283
284 In addition to AtomicAttribute's keywords, you can use ``strip`` (default
285 false) to have leading and trailing whitespace be removed on parse.
286 (Unparsing will not add it back).
287
288 You can also add ``expand`` (default False) to have UnicodeAttribute
289 try and expand RD macros on the instance passed in. This of course
290 only works if the attribute lives on a class that is a MacroPackage.
291 """
292
293 typeDesc_ = "unicode string"
294
295 def parse(self, value: Optional[str]) -> Optional[str]:
296 return PostprocessedTextAttribute.parse(self, value)
297
298 def unparse(self, value: Optional[str]) -> Optional[str]:
299 if value is None:
300 if self.nullLiteral is None:
301 raise ValueError("Unparse None without a null literal can't work.")
302 return self.nullLiteral
303 return value
304
305
306 class NWUnicodeAttribute(UnicodeAttribute):
307 """A UnicodeAttribute that has its whitespace normalized.
308
309 Normalization consists of stripping whitespace at the ends and replacing
310 any runs or internal whitespace by a single blank. The whitespace
311 will not be added back on unparsing.
312 """
313 typeDesc_ = "whitespace normalized unicode string"
314
315 def parse(self, value: Optional[str]) -> Optional[str]:
316 value = UnicodeAttribute.parse(self, value)
317 if value is None:
318 return value
319 return re.sub(r"\s+", " ", value.strip())
320
321
322 class FunctionRelativePathAttribute(UnicodeAttribute):
323 """A (utf-8 encoded) path relative to the result of some function
324 at runtime.
325
326 This is used to make things relative to config items.
327 """
328 def __init__(self,
329 name: str,
330 baseFunction: Callable,
331 default: Union[str, _NullLikeType] = None,
332 description: str = "Undocumented",
333 **kwargs: Any) -> None:
334 kwargs["strip"] = kwargs.get("strip", True)
335 UnicodeAttribute.__init__(self, name, default=default,
336 description=description, **kwargs)
337 self.baseFunction = baseFunction
338 self.hiddenAttName = "_real_"+self.name_
339
340 def parse(self, value: Optional[str]) -> Any:
341 return value
342
343 def unparse(self, value: Any) -> Optional[str]:
344 return value
345
346 def iterParentMethods(self):
347 def computePath(instance: Structure
348 ) -> Union[str, None, utils.NotGivenType]:
349 relative = getattr(instance, self.hiddenAttName)
350 if relative is Undefined:
351 raise utils.StructureError("Attribute %s is mandatory"%self.name_)
352 if relative is NotGiven or relative is None:
353 return relative
354
355 return os.path.join(self.baseFunction(instance), relative)
356
357 def setRelative(
358 instance: Structure,
359 value: Union[bool, _NullLikeType]) -> None:
360 setattr(instance, self.hiddenAttName, value)
361
362 yield (self.name_, property(computePath, setRelative))
363
364
365 class EnumeratedUnicodeAttribute(UnicodeAttribute):
366 """An attribute definition for an item that can only take on one
367 of a finite set of values.
368 """
369 def __init__(self,
370 name: str,
371 default: Union[str, _NullLikeType],
372 validValues: List[str],
373 **kwargs: Any) -> None:
374 kwargs["strip"] = kwargs.get("strip", True)
375 UnicodeAttribute.__init__(self, name, default=default, **kwargs)
376 self.validValues = set(validValues)
377
378 # I'm shutting up mypy here beause it disagrees with my
379 @property
380 def typeDesc_(self) -> str: # type: ignore
381 return "One of: %s"%", ".join(sorted(self.validValues))
382
383 def parse(self, value: Optional[str]) -> Optional[str]:
384 value = UnicodeAttribute.parse(self, value)
385 if not value in self.validValues:
386 raise LiteralParseError(self.name_, value,
387 hint="Valid values include %s"%",".join(self.validValues))
388 return value
389
390
391 class IntAttribute(AtomicAttribute):
392 """An attribute definition for integer attributes.
393 """
394
395 typeDesc_ = "integer"
396
397 def parse(self, value: Optional[str]) -> Optional[int]:
398 try:
399 if value is not None:
400 return int(value)
401 except ValueError:
402 raise utils.logOldExc(
403 LiteralParseError(self.name_, value, hint="Value must be an"
404 " integer literal."))
405 return None
406
407 def unparse(self, value: Optional[int]) -> Optional[str]:
408 return str(value)
409
410
411 class FloatAttribute(AtomicAttribute):
412 """An attribute definition for floating point attributes.
413 """
414
415 typeDesc_ = "float"
416
417 def parse(self, value: Optional[str]) -> Optional[float]:
418 try:
419 if value is not None:
420 return float(value)
421 except ValueError:
422 raise utils.logOldExc(
423 LiteralParseError(self.name_, value, hint="value must be a float"
424 " literal"))
425 return None
426
427 def unparse(self, value: Optional[float]) -> str:
428 return str(value)
429
430
431 class BooleanAttribute(AtomicAttribute):
432 """A boolean attribute.
433
434 Boolean literals are strings like True, false, on, Off, yes, No in
435 some capitalization.
436 """
437 typeDesc_ = "boolean"
438
439 def parse(self, value: str) -> bool:
440 try:
441 return literals.parseBooleanLiteral(value)
442 except ValueError:
443 raise utils.logOldExc(LiteralParseError(
444 self.name_,
445 value,
446 hint= "A boolean literal (e.g., True, False, yes, no)"
447 " is expected here."))
448
449 def unparse(self, value: bool) -> str:
450 return {True: "True", False: "False"}[value]
451
452
453 class StringListAttribute(PostprocessedTextAttribute):
454 """An attribute containing a list of comma separated strings.
455
456 The value is a list. This is similar to a complexattrs.ListOfAtoms
457 with UnicodeAttribute items, except the literal is easier to write
458 but more limited. Use this for the user's convenience.
459 """
460 typeDesc_ = "Comma-separated list of strings"
461 realDefault: List[str] = []
462
463 def __init__(self, name: str, **kwargs: Any) -> None:
464 if "default" in kwargs:
465 self.realDefault = kwargs.pop("default")
466 PostprocessedTextAttribute.__init__(
467 self, name, default=Computed, **kwargs)
468
469 def parse(self, value: Optional[str]) -> List[str]:
470 value = PostprocessedTextAttribute.parse(self, value)
471 if value is not None:
472 return [str(item.strip())
473 for item in value.split(",") if item.strip()]
474 return []
475
476 @property
477 def default_(self) -> Any:
478 try:
479 return self.realDefault[:]
480 except TypeError: # Not iterable; that's the client's problem.
481 return self.realDefault
482
483 @staticmethod
484 def _unparseSingle(v):
485 if hasattr(v, "unparse"):
486 # that's mainly for QuotedName-s
487 return v.unparse()
488 else:
489 return v
490
491 def unparse(self, value: Union[List[str], Set[str]]) -> str:
492 return ", ".join(self._unparseSingle(v) for v in value)
493
494
495 class StringSetAttribute(StringListAttribute):
496 """A StringListAttribute, except the result is a set.
497 """
498 # let me be lazy here and not introduce another intermediate abstract
499 # class; it's too easy to reuse all of StringListAttribute
500
501 realDefault: set = set() # type: ignore
502
503 def parse(self, value: str) -> Set[str]: # type: ignore
504 return set(StringListAttribute.parse(self, value))
505
506 @property
507 def default_(self) -> Union[Set, frozenset]:
508 return self.realDefault.copy()
509
510
511 class IdMapAttribute(AtomicAttribute):
512 """An attribute allowing a quick specification of identifiers to
513 identifiers.
514
515 The literal format is <id>:<id>{,<id>:<id>},? with ignored whitespace.
516 """
517 typeDesc_ = "Comma-separated list of <identifier>:<identifier> pairs"
518
519 def parse(self, val: str) -> Dict[str, str]:
520 if val is None:
521 return None
522 val = val.strip().rstrip(",")
523 res = {}
524 for part in val.split(","):
525 try:
526 left, right = part.split(":")
527 res[left.strip()] = right.strip()
528 except ValueError:
529 raise LiteralParseError(self.name_, val,
530 hint=f"The offending text in the value is '{part}'")
531 return res
532
533 def unparse(self, val: Optional[Dict[str, str]]) -> Optional[str]:
534 if val is None:
535 return None
536 return ", ".join(["%s: %s"%(k, v) for k, v in val.items()])
537
538
539 class ActionAttribute(UnicodeAttribute):
540 """An attribute definition for attributes triggering a method call
541 on the parent instance.
542
543 They do create an attribute on parent which is None by default
544 and the attribute value as a unicode string once the attribute
545 was encountered. This could be used to handle multiple occurrences
546 but is not in this basic definition.
547 """
548 def __init__(self,
549 name: str,
550 methodName: str,
551 description: str = "Undocumented",
552 **kwargs: Any) -> None:
553 kwargs["strip"] = kwargs.get("strip", True)
554 self.methodName = methodName
555 UnicodeAttribute.__init__(self, name, default=None,
556 description=description, **kwargs)
557
558 def feed(self,
559 ctx: StructParseContext,
560 instance: Structure,
561 value: str) -> None:
562 UnicodeAttribute.feed(self, ctx, instance, value)
563 getattr(instance, self.methodName)(ctx)
564
565
566 # __init__ does an import * from this. You shouldn't.
567
568 __all__ = ["LiteralParseError", "Undefined", "UnicodeAttribute",
569 "IntAttribute", "BooleanAttribute", "AtomicAttribute",
570 "EnumeratedUnicodeAttribute", "AttributeDef", "Computed",
571 "FunctionRelativePathAttribute",
572 "StringListAttribute", "ActionAttribute", "FloatAttribute",
573 "StringSetAttribute", "NotGiven", "IdMapAttribute",
574 "NWUnicodeAttribute", "RawAttribute"]