File: formatters.py

package info (click to toggle)
python-tksheet 7.4.16%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,560 kB
  • sloc: python: 25,406; sh: 27; makefile: 2
file content (331 lines) | stat: -rw-r--r-- 9,764 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
from __future__ import annotations

from collections.abc import Callable
from contextlib import suppress
from typing import Any

from .constants import falsy, nonelike, truthy


def is_none_like(o: Any) -> bool:
    return (isinstance(o, str) and o.lower().replace(" ", "") in nonelike) or o in nonelike


def to_int(o: Any, **kwargs) -> int:
    if isinstance(o, int):
        return o
    return int(float(o))


def to_float(o: Any, **kwargs) -> float:
    if isinstance(o, float):
        return o
    return float(o)


def to_percentage(o: Any, **kwargs) -> float:
    if isinstance(o, float):
        return o
    if isinstance(o, str) and o.endswith("%"):
        return float(o.replace("%", "")) / 100
    return float(o)


def alt_to_percentage(o: Any, **kwargs) -> float:
    if isinstance(o, float):
        return o
    if isinstance(o, str) and o.endswith("%"):
        return float(o.replace("%", ""))
    return float(o)


def to_bool(val: Any, **kwargs) -> bool:
    if isinstance(val, bool):
        return val
    v = val.lower() if isinstance(val, str) else val
    _truthy = kwargs.get("truthy", truthy)
    _falsy = kwargs.get("falsy", falsy)
    if v in _truthy:
        return True
    elif v in _falsy:
        return False
    raise ValueError(f'Cannot map "{val}" to bool.')


def try_to_bool(o: Any, **kwargs) -> Any:
    try:
        return to_bool(o)
    except Exception:
        return o


def is_bool_like(o: Any, **kwargs) -> bool:
    try:
        to_bool(o)
        return True
    except Exception:
        return False


def to_str(o: Any, **kwargs: dict) -> str:
    return f"{o}"


def float_to_str(v: Any, **kwargs: dict) -> str:
    if isinstance(v, float):
        if v.is_integer():
            return f"{int(v)}"
        if "decimals" in kwargs and isinstance(kwargs["decimals"], int):
            if kwargs["decimals"]:
                return f"{round(v, kwargs['decimals'])}"
            return f"{int(round(v, kwargs['decimals']))}"
    return f"{v}"


def percentage_to_str(v: Any, **kwargs: dict) -> str:
    if isinstance(v, (int, float)):
        x = v * 100
        if isinstance(x, float):
            if x.is_integer():
                return f"{int(x)}%"
            if "decimals" in kwargs and isinstance(kwargs["decimals"], int):
                if kwargs["decimals"]:
                    return f"{round(x, kwargs['decimals'])}%"
                return f"{int(round(x, kwargs['decimals']))}%"
        return f"{x}%"
    return f"{v}%"


def alt_percentage_to_str(v: Any, **kwargs: dict) -> str:
    return f"{float_to_str(v)}%"


def bool_to_str(v: Any, **kwargs: dict) -> str:
    return f"{v}"


def int_formatter(
    datatypes: tuple[Any] | Any = int,
    format_function: Callable = to_int,
    to_str_function: Callable = to_str,
    **kwargs,
) -> dict:
    return formatter(
        datatypes=datatypes,
        format_function=format_function,
        to_str_function=to_str_function,
        **kwargs,
    )


def float_formatter(
    datatypes: tuple[Any] | Any = float,
    format_function: Callable = to_float,
    to_str_function: Callable = float_to_str,
    decimals: int = 2,
    **kwargs,
) -> dict:
    return formatter(
        datatypes=datatypes,
        format_function=format_function,
        to_str_function=to_str_function,
        decimals=decimals,
        **kwargs,
    )


def percentage_formatter(
    datatypes: tuple[Any] | Any = float,
    format_function: Callable = to_percentage,
    to_str_function: Callable = percentage_to_str,
    decimals: int = 2,
    **kwargs,
) -> dict:
    return formatter(
        datatypes=datatypes,
        format_function=format_function,
        to_str_function=to_str_function,
        decimals=decimals,
        **kwargs,
    )


def bool_formatter(
    datatypes: tuple[Any] | Any = bool,
    format_function: Callable = to_bool,
    to_str_function: Callable = bool_to_str,
    invalid_value: Any = "NA",
    truthy_values: set[Any] = truthy,
    falsy_values: set[Any] = falsy,
    **kwargs,
) -> dict:
    return formatter(
        datatypes=datatypes,
        format_function=format_function,
        to_str_function=to_str_function,
        invalid_value=invalid_value,
        truthy_values=truthy_values,
        falsy_values=falsy_values,
        **kwargs,
    )


def formatter(
    datatypes: tuple[Any] | Any,
    format_function: Callable,
    to_str_function: Callable = to_str,
    invalid_value: Any = "NaN",
    nullable: bool = True,
    pre_format_function: Callable | None = None,
    post_format_function: Callable | None = None,
    clipboard_function: Callable | None = None,
    **kwargs,
) -> dict:
    return {
        **{
            "datatypes": datatypes,
            "format_function": format_function,
            "to_str_function": to_str_function,
            "invalid_value": invalid_value,
            "nullable": nullable,
            "pre_format_function": pre_format_function,
            "post_format_function": post_format_function,
            "clipboard_function": clipboard_function,
        },
        **kwargs,
    }


def format_data(
    value: Any = "",
    datatypes: tuple[Any] | Any = int,
    nullable: bool = True,
    pre_format_function: Callable | None = None,
    format_function: Callable | None = to_int,
    post_format_function: Callable | None = None,
    **kwargs,
) -> Any:
    if pre_format_function:
        value = pre_format_function(value)
    if nullable and is_none_like(value):
        value = None
    else:
        with suppress(Exception):
            value = format_function(value, **kwargs)
    if post_format_function and isinstance(value, datatypes):
        value = post_format_function(value)
    return value


def data_to_str(
    value: Any = "",
    datatypes: tuple[Any] | Any = int,
    nullable: bool = True,
    invalid_value: Any = "NaN",
    to_str_function: Callable | None = None,
    **kwargs,
) -> str:
    if not isinstance(value, datatypes):
        return invalid_value
    if value is None and nullable:
        return ""
    return to_str_function(value, **kwargs)


def get_data_with_valid_check(value="", datatypes: tuple[()] | tuple[Any] | Any = (), invalid_value="NA"):
    if isinstance(value, datatypes):
        return value
    return invalid_value


def get_clipboard_data(value: Any = "", clipboard_function: Callable | None = None, **kwargs: dict) -> Any:
    if clipboard_function is not None:
        return clipboard_function(value, **kwargs)
    if isinstance(value, (str, int, float, bool)):
        return value
    return data_to_str(value, **kwargs)


class Formatter:
    def __init__(
        self,
        value: Any,
        datatypes: tuple[Any],
        format_function: Callable = to_int,
        to_str_function: Callable = to_str,
        nullable: bool = True,
        invalid_value: str = "NaN",
        pre_format_function: Callable | None = None,
        post_format_function: Callable | None = None,
        clipboard_function: Callable | None = None,
        **kwargs,
    ) -> None:
        if nullable:
            if isinstance(datatypes, (list, tuple)):
                datatypes = tuple(set(datatypes) | {type(None)})
            else:
                datatypes = (datatypes, type(None))
        elif isinstance(datatypes, (list, tuple)) and type(None) in datatypes or datatypes is type(None):
            raise TypeError("Non-nullable cells cannot have NoneType as a datatype.")
        self.kwargs = kwargs
        self.valid_datatypes = datatypes
        self.format_function = format_function
        self.to_str_function = to_str_function
        self.nullable = nullable
        self.invalid_value = invalid_value
        self.pre_format_function = pre_format_function
        self.post_format_function = post_format_function
        self.clipboard_function = clipboard_function
        try:
            self.value = self.format_data(value)
        except Exception:
            self.value = f"{value}"

    def __str__(self) -> Any:
        if not self.valid():
            return self.invalid_value
        if self.value is None and self.nullable:
            return ""
        return self.to_str_function(self.value, **self.kwargs)

    def valid(self, value: Any = None) -> bool:
        if value is None:
            value = self.value
        return isinstance(value, self.valid_datatypes)

    def format_data(self, value: Any) -> Any:
        if self.pre_format_function:
            value = self.pre_format_function(value)
        value = None if (self.nullable and is_none_like(value)) else self.format_function(value, **self.kwargs)
        if self.post_format_function and self.valid(value):
            value = self.post_format_function(value)
        return value

    def get_data_with_valid_check(self) -> Any:
        if self.valid():
            return self.value
        return self.invalid_value

    def get_clipboard_data(self) -> Any:
        if self.clipboard_function is not None:
            return self.clipboard_function(self.value, **self.kwargs)
        if isinstance(self.value, (int, float, bool)):
            return self.value
        return self.__str__()

    def __eq__(self, __value: Any) -> bool:
        # in case of custom formatter class
        # compare the values
        try:
            if hasattr(__value, "value"):
                return self.value == __value.value
        except Exception:
            pass
        # if comparing to a string, format the string and compare
        if isinstance(__value, str):
            try:
                return self.value == self.format_data(__value)
            except Exception:
                pass
        # if comparing to anything else, compare the values
        return self.value == __value