Coverage for src/appl/core/promptable/definition.py: 93%
41 statements
« prev ^ index » next coverage.py v7.6.7, created at 2024-11-22 15:39 -0800
« prev ^ index » next coverage.py v7.6.7, created at 2024-11-22 15:39 -0800
1from ..types import *
2from .base import Promptable
3from .formatter import Formattable, FormatterMeta
6class Definition(Promptable, Formattable):
7 """Represent a definition of a concept.
9 Attributes:
10 fstr: The format string for the definition.
11 name: The name of the definition.
12 desc: A description of the definition.
13 _forks: A list of all instances of this class.
14 """
16 fstr: str = "{}"
17 name: Optional[String] = None
18 desc: String = ""
19 _forks: List["Definition"] = []
21 def __init__(
22 self,
23 name: Optional[String] = None,
24 desc: Optional[String] = None,
25 *,
26 sep: String = ": ",
27 details: Any = None,
28 fstr: Optional[str] = None,
29 var_name: Optional[str] = None,
30 ):
31 """Initialize the Definition with the given name and description.
33 Args:
34 name: The name of the definition.
35 desc: A description of the definition.
36 sep: The separator between the name and description.
37 details: Additional details about the definition.
38 fstr: The format string for the definition.
39 var_name: The name of the variable that the definition is stored in.
40 """
41 self.name = name or self.name or self.__doc__
42 if self.name is None:
43 raise ValueError("Name must be provided for Definition.")
45 if desc is not None:
46 self.desc = desc
47 self.sep = sep
48 self.details = details
49 if fstr is not None:
50 self.fstr = fstr
51 self.var_name = var_name or self.name
53 self._forks.append(self)
55 def __hash__(self) -> int:
56 return hash(self.var_name)
58 def __prompt__(self) -> List[Any]:
59 # Used when add the Definition to the prompt
60 desc = self.desc or ""
61 res = [f"{self.name}{self.sep}{desc}"]
62 if self.details is not None:
63 res.append(self.details)
64 return res
66 def __repr__(self):
67 # Used to display information
68 desc = self.desc or ""
69 s = f"{self.name}{self.sep}{desc}"
70 if self.details is not None:
71 s += f"\n{self.details}"
72 return s
74 def __str__(self):
75 # Used for reference in the prompt
76 return self.fstr.format(self.name)
79class BracketedDefinition(Definition):
80 """A Definition that is formatted with square brackets."""
82 fstr = "[{}]"
85def define(def_name: str, format_str: str = "{}") -> type:
86 """Create a new Definition subclass with the given name and format string."""
88 class CustomDef(Definition):
89 name = def_name
90 fstr = format_str
92 return CustomDef
95def define_bracketed(def_name: str) -> type:
96 """Create a new BracketedDefinition subclass with the given name."""
98 class CustomDef(BracketedDefinition):
99 name = def_name
101 return CustomDef