Debian Codegraph @

pint/facets/group/definitions.py

raw
1 """
2 pint.facets.group.definitions
3 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
5 :copyright: 2022 by Pint Authors, see AUTHORS for more details.
6 :license: BSD, see LICENSE for more details.
7 """
8
9 from __future__ import annotations
10
11 from collections.abc import Iterable
12 from dataclasses import dataclass
13
14 from ... import errors
15 from ...compat import Self
16 from .. import plain
17
18
19 @dataclass(frozen=True)
20 class GroupDefinition(errors.WithDefErr):
21 """Definition of a group."""
22
23 #: name of the group
24 name: str
25 #: unit groups that will be included within the group
26 using_group_names: tuple[str, ...]
27 #: definitions for the units existing within the group
28 definitions: tuple[plain.UnitDefinition, ...]
29
30 @classmethod
31 def from_lines(
32 cls: type[Self], lines: Iterable[str], non_int_type: type
33 ) -> Self | None:
34 # TODO: this is to keep it backwards compatible
35 from ...delegates import ParserConfig, txt_defparser
36
37 cfg = ParserConfig(non_int_type)
38 parser = txt_defparser.DefParser(cfg, None)
39 pp = parser.parse_string("\n".join(lines) + "\n@end")
40 for definition in parser.iter_parsed_project(pp):
41 if isinstance(definition, cls):
42 return definition
43
44 @property
45 def unit_names(self) -> tuple[str, ...]:
46 return tuple(el.name for el in self.definitions)
47
48 def __post_init__(self) -> None:
49 if not errors.is_valid_group_name(self.name):
50 raise self.def_err(errors.MSG_INVALID_GROUP_NAME)
51
52 for k in self.using_group_names:
53 if not errors.is_valid_group_name(k):
54 raise self.def_err(
55 f"refers to '{k}' that " + errors.MSG_INVALID_GROUP_NAME
56 )