Debian Codegraph @

pint/delegates/txt_defparser/defaults.py

raw
1 """
2 pint.delegates.txt_defparser.defaults
3 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
5 Definitions for parsing Default sections.
6
7 See each one for a slighly longer description of the
8 syntax.
9
10 :copyright: 2022 by Pint Authors, see AUTHORS for more details.
11 :license: BSD, see LICENSE for more details.
12 """
13
14 from __future__ import annotations
15
16 import typing as ty
17 from dataclasses import dataclass, fields
18
19 import flexparser as fp
20
21 from ...facets.plain import definitions
22 from ..base_defparser import PintParsedStatement
23 from . import block, plain
24
25
26 @dataclass(frozen=True)
27 class BeginDefaults(PintParsedStatement):
28 """Being of a defaults directive.
29
30 @defaults
31 """
32
33 @classmethod
34 def from_string(cls, s: str) -> fp.NullableParsedResult[BeginDefaults]:
35 if s.strip() == "@defaults":
36 return cls()
37 return None
38
39
40 @dataclass(frozen=True)
41 class DefaultsDefinition(
42 block.DirectiveBlock[
43 definitions.DefaultsDefinition,
44 BeginDefaults,
45 ty.Union[
46 plain.CommentDefinition,
47 plain.Equality,
48 ],
49 ]
50 ):
51 """Directive to store values.
52
53 @defaults
54 system = mks
55 @end
56
57 See Equality and Comment for more parsing related information.
58 """
59
60 @property
61 def _valid_fields(self) -> tuple[str, ...]:
62 return tuple(f.name for f in fields(definitions.DefaultsDefinition))
63
64 def derive_definition(self) -> definitions.DefaultsDefinition:
65 for definition in self.filter_by(plain.Equality):
66 if definition.lhs not in self._valid_fields:
67 raise ValueError(
68 f"`{definition.lhs}` is not a valid key "
69 f"for the default section. {self._valid_fields}"
70 )
71
72 return definitions.DefaultsDefinition(
73 *tuple(self.get_key(key) for key in self._valid_fields)
74 )
75
76 def get_key(self, key: str) -> str:
77 for stmt in self.body:
78 if isinstance(stmt, plain.Equality) and stmt.lhs == key:
79 return stmt.rhs
80 raise KeyError(key)