Debian Codegraph @

tksheet/formatters.py

raw symbols SCIP
1 from __future__ import annotations
2
3 from collections.abc import Callable
4 from contextlib import suppress
5 from typing import Any
6
7 from .constants import falsy, nonelike, truthy
8
9
10 def is_none_like(o: Any) -> bool:
11 return (isinstance(o, str) and o.lower().replace(" ", "") in nonelike) or o in nonelike
12
13
14 def to_int(o: Any, **kwargs) -> int:
15 if isinstance(o, int):
16 return o
17 return int(float(o))
18
19
20 def to_float(o: Any, **kwargs) -> float:
21 if isinstance(o, float):
22 return o
23 return float(o)
24
25
26 def to_percentage(o: Any, **kwargs) -> float:
27 if isinstance(o, float):
28 return o
29 if isinstance(o, str) and o.endswith("%"):
30 return float(o.replace("%", "")) / 100
31 return float(o)
32
33
34 def alt_to_percentage(o: Any, **kwargs) -> float:
35 if isinstance(o, float):
36 return o
37 if isinstance(o, str) and o.endswith("%"):
38 return float(o.replace("%", ""))
39 return float(o)
40
41
42 def to_bool(val: Any, **kwargs) -> bool:
43 if isinstance(val, bool):
44 return val
45 v = val.lower() if isinstance(val, str) else val
46 _truthy = kwargs.get("truthy", truthy)
47 _falsy = kwargs.get("falsy", falsy)
48 if v in _truthy:
49 return True
50 elif v in _falsy:
51 return False
52 raise ValueError(f'Cannot map "{val}" to bool.')
53
54
55 def try_to_bool(o: Any, **kwargs) -> Any:
56 try:
57 return to_bool(o)
58 except Exception:
59 return o
60
61
62 def is_bool_like(o: Any, **kwargs) -> bool:
63 try:
64 to_bool(o)
65 return True
66 except Exception:
67 return False
68
69
70 def to_str(o: Any, **kwargs: dict) -> str:
71 return f"{o}"
72
73
74 def float_to_str(v: Any, **kwargs: dict) -> str:
75 if isinstance(v, float):
76 if v.is_integer():
77 return f"{int(v)}"
78 if "decimals" in kwargs and isinstance(kwargs["decimals"], int):
79 if kwargs["decimals"]:
80 return f"{round(v, kwargs['decimals'])}"
81 return f"{int(round(v, kwargs['decimals']))}"
82 return f"{v}"
83
84
85 def percentage_to_str(v: Any, **kwargs: dict) -> str:
86 if isinstance(v, (int, float)):
87 x = v * 100
88 if isinstance(x, float):
89 if x.is_integer():
90 return f"{int(x)}%"
91 if "decimals" in kwargs and isinstance(kwargs["decimals"], int):
92 if kwargs["decimals"]:
93 return f"{round(x, kwargs['decimals'])}%"
94 return f"{int(round(x, kwargs['decimals']))}%"
95 return f"{x}%"
96 return f"{v}%"
97
98
99 def alt_percentage_to_str(v: Any, **kwargs: dict) -> str:
100 return f"{float_to_str(v)}%"
101
102
103 def bool_to_str(v: Any, **kwargs: dict) -> str:
104 return f"{v}"
105
106
107 def int_formatter(
108 datatypes: tuple[Any] | Any = int,
109 format_function: Callable = to_int,
110 to_str_function: Callable = to_str,
111 **kwargs,
112 ) -> dict:
113 return formatter(
114 datatypes=datatypes,
115 format_function=format_function,
116 to_str_function=to_str_function,
117 **kwargs,
118 )
119
120
121 def float_formatter(
122 datatypes: tuple[Any] | Any = float,
123 format_function: Callable = to_float,
124 to_str_function: Callable = float_to_str,
125 decimals: int = 2,
126 **kwargs,
127 ) -> dict:
128 return formatter(
129 datatypes=datatypes,
130 format_function=format_function,
131 to_str_function=to_str_function,
132 decimals=decimals,
133 **kwargs,
134 )
135
136
137 def percentage_formatter(
138 datatypes: tuple[Any] | Any = float,
139 format_function: Callable = to_percentage,
140 to_str_function: Callable = percentage_to_str,
141 decimals: int = 2,
142 **kwargs,
143 ) -> dict:
144 return formatter(
145 datatypes=datatypes,
146 format_function=format_function,
147 to_str_function=to_str_function,
148 decimals=decimals,
149 **kwargs,
150 )
151
152
153 def bool_formatter(
154 datatypes: tuple[Any] | Any = bool,
155 format_function: Callable = to_bool,
156 to_str_function: Callable = bool_to_str,
157 invalid_value: Any = "NA",
158 truthy_values: set[Any] = truthy,
159 falsy_values: set[Any] = falsy,
160 **kwargs,
161 ) -> dict:
162 return formatter(
163 datatypes=datatypes,
164 format_function=format_function,
165 to_str_function=to_str_function,
166 invalid_value=invalid_value,
167 truthy_values=truthy_values,
168 falsy_values=falsy_values,
169 **kwargs,
170 )
171
172
173 def formatter(
174 datatypes: tuple[Any] | Any,
175 format_function: Callable,
176 to_str_function: Callable = to_str,
177 invalid_value: Any = "NaN",
178 nullable: bool = True,
179 pre_format_function: Callable | None = None,
180 post_format_function: Callable | None = None,
181 clipboard_function: Callable | None = None,
182 **kwargs,
183 ) -> dict:
184 return {
185 **{
186 "datatypes": datatypes,
187 "format_function": format_function,
188 "to_str_function": to_str_function,
189 "invalid_value": invalid_value,
190 "nullable": nullable,
191 "pre_format_function": pre_format_function,
192 "post_format_function": post_format_function,
193 "clipboard_function": clipboard_function,
194 },
195 **kwargs,
196 }
197
198
199 def format_data(
200 value: Any = "",
201 datatypes: tuple[Any] | Any = int,
202 nullable: bool = True,
203 pre_format_function: Callable | None = None,
204 format_function: Callable | None = to_int,
205 post_format_function: Callable | None = None,
206 **kwargs,
207 ) -> Any:
208 if pre_format_function:
209 value = pre_format_function(value)
210 if nullable and is_none_like(value):
211 value = None
212 else:
213 with suppress(Exception):
214 value = format_function(value, **kwargs)
215 if post_format_function and isinstance(value, datatypes):
216 value = post_format_function(value)
217 return value
218
219
220 def data_to_str(
221 value: Any = "",
222 datatypes: tuple[Any] | Any = int,
223 nullable: bool = True,
224 invalid_value: Any = "NaN",
225 to_str_function: Callable | None = None,
226 **kwargs,
227 ) -> str:
228 if not isinstance(value, datatypes):
229 return invalid_value
230 if value is None and nullable:
231 return ""
232 return to_str_function(value, **kwargs)
233
234
235 def get_data_with_valid_check(value="", datatypes: tuple[()] | tuple[Any] | Any = (), invalid_value="NA"):
236 if isinstance(value, datatypes):
237 return value
238 return invalid_value
239
240
241 def get_clipboard_data(value: Any = "", clipboard_function: Callable | None = None, **kwargs: dict) -> Any:
242 if clipboard_function is not None:
243 return clipboard_function(value, **kwargs)
244 if isinstance(value, (str, int, float, bool)):
245 return value
246 return data_to_str(value, **kwargs)
247
248
249 class Formatter:
250 def __init__(
251 self,
252 value: Any,
253 datatypes: tuple[Any],
254 format_function: Callable = to_int,
255 to_str_function: Callable = to_str,
256 nullable: bool = True,
257 invalid_value: str = "NaN",
258 pre_format_function: Callable | None = None,
259 post_format_function: Callable | None = None,
260 clipboard_function: Callable | None = None,
261 **kwargs,
262 ) -> None:
263 if nullable:
264 if isinstance(datatypes, (list, tuple)):
265 datatypes = tuple(set(datatypes) | {type(None)})
266 else:
267 datatypes = (datatypes, type(None))
268 elif isinstance(datatypes, (list, tuple)) and type(None) in datatypes or datatypes is type(None):
269 raise TypeError("Non-nullable cells cannot have NoneType as a datatype.")
270 self.kwargs = kwargs
271 self.valid_datatypes = datatypes
272 self.format_function = format_function
273 self.to_str_function = to_str_function
274 self.nullable = nullable
275 self.invalid_value = invalid_value
276 self.pre_format_function = pre_format_function
277 self.post_format_function = post_format_function
278 self.clipboard_function = clipboard_function
279 try:
280 self.value = self.format_data(value)
281 except Exception:
282 self.value = f"{value}"
283
284 def __str__(self) -> Any:
285 if not self.valid():
286 return self.invalid_value
287 if self.value is None and self.nullable:
288 return ""
289 return self.to_str_function(self.value, **self.kwargs)
290
291 def valid(self, value: Any = None) -> bool:
292 if value is None:
293 value = self.value
294 return isinstance(value, self.valid_datatypes)
295
296 def format_data(self, value: Any) -> Any:
297 if self.pre_format_function:
298 value = self.pre_format_function(value)
299 value = None if (self.nullable and is_none_like(value)) else self.format_function(value, **self.kwargs)
300 if self.post_format_function and self.valid(value):
301 value = self.post_format_function(value)
302 return value
303
304 def get_data_with_valid_check(self) -> Any:
305 if self.valid():
306 return self.value
307 return self.invalid_value
308
309 def get_clipboard_data(self) -> Any:
310 if self.clipboard_function is not None:
311 return self.clipboard_function(self.value, **self.kwargs)
312 if isinstance(self.value, (int, float, bool)):
313 return self.value
314 return self.__str__()
315
316 def __eq__(self, __value: Any) -> bool:
317 # in case of custom formatter class
318 # compare the values
319 try:
320 if hasattr(__value, "value"):
321 return self.value == __value.value
322 except Exception:
323 pass
324 # if comparing to a string, format the string and compare
325 if isinstance(__value, str):
326 try:
327 return self.value == self.format_data(__value)
328 except Exception:
329 pass
330 # if comparing to anything else, compare the values
331 return self.value == __value