derafu-support 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- derafu_support/__init__.py +6 -0
- derafu_support/dates.py +281 -0
- derafu_support/dictionary_file_operations.py +74 -0
- derafu_support/dictionary_merge.py +47 -0
- derafu_support/encoding.py +24 -0
- derafu_support/exceptions.py +21 -0
- derafu_support/gravatar.py +29 -0
- derafu_support/is_empty.py +124 -0
- derafu_support/is_set.py +94 -0
- derafu_support/log.py +372 -0
- derafu_support/number_format.py +56 -0
- derafu_support/py.typed +0 -0
- derafu_support-1.0.0.dist-info/METADATA +70 -0
- derafu_support-1.0.0.dist-info/RECORD +17 -0
- derafu_support-1.0.0.dist-info/WHEEL +5 -0
- derafu_support-1.0.0.dist-info/licenses/LICENSE +21 -0
- derafu_support-1.0.0.dist-info/top_level.txt +1 -0
derafu_support/dates.py
ADDED
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Functions for tax periods (YYYYMM), dates and month names.
|
|
3
|
+
|
|
4
|
+
A period is an integer with the year and month (``202611``). Dates are
|
|
5
|
+
received and returned as ``YYYY-MM-DD`` strings.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from datetime import UTC, date, datetime, timedelta
|
|
9
|
+
|
|
10
|
+
# length of a monthly period (YYYYMM) and of a yearly one (YYYY)
|
|
11
|
+
_MONTHLY_PERIOD_LENGTH = 6
|
|
12
|
+
_YEARLY_PERIOD_LENGTH = 4
|
|
13
|
+
# month left after subtracting or adding a month without adjusting the year
|
|
14
|
+
_MONTH_BEFORE_JANUARY = 0
|
|
15
|
+
_MONTH_AFTER_DECEMBER = 13
|
|
16
|
+
# months in a year
|
|
17
|
+
_MONTHS_PER_YEAR = 12
|
|
18
|
+
# parts of a date and time with minutes ("31/12/2026 10:30")
|
|
19
|
+
_DATE_TIME_PARTS = 2
|
|
20
|
+
_HOUR_MINUTES_LENGTH = 5
|
|
21
|
+
|
|
22
|
+
_MONTH_NAMES = (
|
|
23
|
+
'enero',
|
|
24
|
+
'febrero',
|
|
25
|
+
'marzo',
|
|
26
|
+
'abril',
|
|
27
|
+
'mayo',
|
|
28
|
+
'junio',
|
|
29
|
+
'julio',
|
|
30
|
+
'agosto',
|
|
31
|
+
'septiembre',
|
|
32
|
+
'octubre',
|
|
33
|
+
'noviembre',
|
|
34
|
+
'diciembre',
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _today() -> date:
|
|
39
|
+
"""
|
|
40
|
+
Return today's date in the system's local time zone.
|
|
41
|
+
|
|
42
|
+
:return: Today's date.
|
|
43
|
+
:rtype: date
|
|
44
|
+
"""
|
|
45
|
+
return datetime.now().astimezone().date()
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def period_current() -> int:
|
|
49
|
+
"""
|
|
50
|
+
Return the current period (YYYYMM).
|
|
51
|
+
|
|
52
|
+
:return: Current period.
|
|
53
|
+
:rtype: int
|
|
54
|
+
"""
|
|
55
|
+
return int(_today().strftime('%Y%m'))
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def period_previous(period: int | None = None) -> int:
|
|
59
|
+
"""
|
|
60
|
+
Return the period before the given one.
|
|
61
|
+
|
|
62
|
+
:param period: Period (YYYYMM). If not given, the current one is used.
|
|
63
|
+
:return: Previous period; January goes to December of the previous year.
|
|
64
|
+
:rtype: int
|
|
65
|
+
"""
|
|
66
|
+
if period is None:
|
|
67
|
+
period = period_current()
|
|
68
|
+
previous_period = period - 1
|
|
69
|
+
if (
|
|
70
|
+
len(str(period)) == _MONTHLY_PERIOD_LENGTH
|
|
71
|
+
and int(str(previous_period)[4:]) == _MONTH_BEFORE_JANUARY
|
|
72
|
+
):
|
|
73
|
+
previous_period = previous_period - 100 + _MONTHS_PER_YEAR
|
|
74
|
+
return previous_period
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def period_next(period: int | None = None) -> int:
|
|
78
|
+
"""
|
|
79
|
+
Return the period after the given one.
|
|
80
|
+
|
|
81
|
+
:param period: Period (YYYYMM). If not given, the current one is used.
|
|
82
|
+
:return: Next period; December goes to January of the next year.
|
|
83
|
+
:rtype: int
|
|
84
|
+
"""
|
|
85
|
+
if period is None:
|
|
86
|
+
period = period_current()
|
|
87
|
+
next_period = period + 1
|
|
88
|
+
if (
|
|
89
|
+
len(str(period)) == _MONTHLY_PERIOD_LENGTH
|
|
90
|
+
and int(str(next_period)[4:]) == _MONTH_AFTER_DECEMBER
|
|
91
|
+
):
|
|
92
|
+
next_period = next_period + 100 - _MONTHS_PER_YEAR
|
|
93
|
+
return next_period
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def period_range(period_from: int, period_to: int | None = None) -> list[int]:
|
|
97
|
+
"""
|
|
98
|
+
Return the periods between two periods, both included.
|
|
99
|
+
|
|
100
|
+
:param period_from: First period (YYYYMM).
|
|
101
|
+
:param period_to: Last period. If not given, the current one is used.
|
|
102
|
+
:return: Periods in order; empty if the first is after the last.
|
|
103
|
+
:rtype: list[int]
|
|
104
|
+
"""
|
|
105
|
+
if period_to is None:
|
|
106
|
+
period_to = period_current()
|
|
107
|
+
periods: list[int] = []
|
|
108
|
+
period = period_from
|
|
109
|
+
while period <= period_to:
|
|
110
|
+
periods.append(period)
|
|
111
|
+
period = period_next(period)
|
|
112
|
+
return periods
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def period_first_day(period: int) -> str:
|
|
116
|
+
"""
|
|
117
|
+
Return the first day of a period.
|
|
118
|
+
|
|
119
|
+
:param period: Period (YYYYMM).
|
|
120
|
+
:return: Date ``YYYY-MM-01``.
|
|
121
|
+
:rtype: str
|
|
122
|
+
"""
|
|
123
|
+
return str(period)[0:4] + '-' + str(period)[4:] + '-01'
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def period_last_day(period: int) -> str:
|
|
127
|
+
"""
|
|
128
|
+
Return the last day of a period.
|
|
129
|
+
|
|
130
|
+
:param period: Period (YYYYMM).
|
|
131
|
+
:return: Date ``YYYY-MM-DD`` of the last day of the month.
|
|
132
|
+
:rtype: str
|
|
133
|
+
"""
|
|
134
|
+
first_day_next_period = date.fromisoformat(
|
|
135
|
+
period_first_day(period_next(period))
|
|
136
|
+
)
|
|
137
|
+
return (first_day_next_period - timedelta(days=1)).isoformat()
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def period_valid(
|
|
141
|
+
period: int | str, year_from: int = 2000, year_to: int = 2100
|
|
142
|
+
) -> bool:
|
|
143
|
+
"""
|
|
144
|
+
Tell whether a period (YYYYMM) or a year (YYYY) is valid.
|
|
145
|
+
|
|
146
|
+
:param period: Period or year, as a number or a string.
|
|
147
|
+
:param year_from: First accepted year.
|
|
148
|
+
:param year_to: Last accepted year.
|
|
149
|
+
:return: True if it is a 4 or 6 digit number with a valid year (and
|
|
150
|
+
month).
|
|
151
|
+
:rtype: bool
|
|
152
|
+
"""
|
|
153
|
+
try:
|
|
154
|
+
int(period)
|
|
155
|
+
except ValueError:
|
|
156
|
+
return False
|
|
157
|
+
period = str(period)
|
|
158
|
+
n_period = len(period)
|
|
159
|
+
if n_period == _YEARLY_PERIOD_LENGTH:
|
|
160
|
+
return year_from <= int(period) <= year_to
|
|
161
|
+
if n_period == _MONTHLY_PERIOD_LENGTH:
|
|
162
|
+
year = int(period[0:4])
|
|
163
|
+
month = int(period[4:])
|
|
164
|
+
return year_from <= year <= year_to and 1 <= month <= _MONTHS_PER_YEAR
|
|
165
|
+
return False
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def date_normalize(
|
|
169
|
+
date: str, format_from: str | None = None, format_to: str | None = None
|
|
170
|
+
) -> str:
|
|
171
|
+
"""
|
|
172
|
+
Change the format of a date (by default, from DD/MM/YYYY to YYYY-MM-DD).
|
|
173
|
+
|
|
174
|
+
Without formats, ``DD/MM/YYYY``, ``DD/MM/YYYY HH:MM`` and
|
|
175
|
+
``DD/MM/YYYY HH:MM:SS`` are recognized, and returned as ``YYYY-MM-DD``,
|
|
176
|
+
``YYYY-MM-DD HH:MM`` and ``YYYY-MM-DD HH:MM:SS``.
|
|
177
|
+
|
|
178
|
+
:param date: Date as a string.
|
|
179
|
+
:param format_from: Input format (``strptime``).
|
|
180
|
+
:param format_to: Output format (``strftime``).
|
|
181
|
+
:return: Date in the output format.
|
|
182
|
+
:rtype: str
|
|
183
|
+
:raises ValueError: If the date does not match the input format.
|
|
184
|
+
:raises TypeError: If ``format_from`` is given but ``format_to`` is not.
|
|
185
|
+
"""
|
|
186
|
+
if format_from is None:
|
|
187
|
+
aux = date.split(' ')
|
|
188
|
+
if len(aux) == _DATE_TIME_PARTS:
|
|
189
|
+
if len(aux[1]) == _HOUR_MINUTES_LENGTH:
|
|
190
|
+
format_from = '%d/%m/%Y %H:%M'
|
|
191
|
+
format_to = '%Y-%m-%d %H:%M'
|
|
192
|
+
else:
|
|
193
|
+
format_from = '%d/%m/%Y %H:%M:%S'
|
|
194
|
+
format_to = '%Y-%m-%d %H:%M:%S'
|
|
195
|
+
else:
|
|
196
|
+
format_from = '%d/%m/%Y'
|
|
197
|
+
format_to = '%Y-%m-%d'
|
|
198
|
+
# the time zone (UTC) only avoids a naive datetime: it does not change
|
|
199
|
+
# the output text unless format_to asks for the zone (%z or %Z)
|
|
200
|
+
date_obj = datetime.strptime(date, format_from).replace(tzinfo=UTC)
|
|
201
|
+
if format_to is None:
|
|
202
|
+
# format_from without format_to: same as datetime.strftime(None)
|
|
203
|
+
msg = 'strftime() argument 1 must be str, not None'
|
|
204
|
+
raise TypeError(msg)
|
|
205
|
+
return date_obj.strftime(format_to)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def date_add_days(days: int, from_date: str | None = None) -> str:
|
|
209
|
+
"""
|
|
210
|
+
Add (or subtract) days to a date.
|
|
211
|
+
|
|
212
|
+
:param days: Days to add; if negative, they are subtracted.
|
|
213
|
+
:param from_date: Date ``YYYY-MM-DD``. If not given, today is used.
|
|
214
|
+
:return: Resulting date ``YYYY-MM-DD``.
|
|
215
|
+
:rtype: str
|
|
216
|
+
"""
|
|
217
|
+
if from_date is None:
|
|
218
|
+
from_date = _today().strftime('%Y-%m-%d')
|
|
219
|
+
y, m, d = from_date.split('-')
|
|
220
|
+
return str(date(int(y), int(m), int(d)) + timedelta(days=days))
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def date_count_days(
|
|
224
|
+
date_from: str | date, date_to: str | date | None = None
|
|
225
|
+
) -> int:
|
|
226
|
+
"""
|
|
227
|
+
Count the days between two dates, regardless of their order.
|
|
228
|
+
|
|
229
|
+
Only the date part (``YYYY-MM-DD``) is used; the time is ignored.
|
|
230
|
+
|
|
231
|
+
:param date_from: Start date (or date and time).
|
|
232
|
+
:param date_to: End date (or date and time). If not given, today is
|
|
233
|
+
used.
|
|
234
|
+
:return: Days between both dates, always positive or zero.
|
|
235
|
+
:rtype: int
|
|
236
|
+
"""
|
|
237
|
+
if date_to is None:
|
|
238
|
+
date_to = _today().strftime('%Y-%m-%d')
|
|
239
|
+
y_from, m_from, d_from = str(date_from).split(' ')[0].split('-')
|
|
240
|
+
y_to, m_to, d_to = str(date_to).split(' ')[0].split('-')
|
|
241
|
+
delta = date(int(y_to), int(m_to), int(d_to)) - date(
|
|
242
|
+
int(y_from), int(m_from), int(d_from)
|
|
243
|
+
)
|
|
244
|
+
return abs(delta.days)
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def month_from_string(month: str) -> str:
|
|
248
|
+
"""
|
|
249
|
+
Return the month number (``01`` to ``12``) from its name.
|
|
250
|
+
|
|
251
|
+
:param month: Month name in Spanish, case-insensitive.
|
|
252
|
+
:return: Two-digit month number, or the given text if it is not a month
|
|
253
|
+
name.
|
|
254
|
+
:rtype: str
|
|
255
|
+
"""
|
|
256
|
+
month_lower = month.lower()
|
|
257
|
+
if month_lower in _MONTH_NAMES:
|
|
258
|
+
return f'{_MONTH_NAMES.index(month_lower) + 1:02d}'
|
|
259
|
+
return month
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def month_from_index(index: int | str) -> str:
|
|
263
|
+
"""
|
|
264
|
+
Return the month name from its index (0 is January).
|
|
265
|
+
|
|
266
|
+
:param index: Month index; the remainder of dividing by 12 is used.
|
|
267
|
+
:return: Month name in Spanish and in lower case.
|
|
268
|
+
:rtype: str
|
|
269
|
+
"""
|
|
270
|
+
return _MONTH_NAMES[int(index) % _MONTHS_PER_YEAR]
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def month_from_number(month: int | str) -> str:
|
|
274
|
+
"""
|
|
275
|
+
Return the month name from its number (1 is January).
|
|
276
|
+
|
|
277
|
+
:param month: Month number.
|
|
278
|
+
:return: Month name in Spanish and in lower case.
|
|
279
|
+
:rtype: str
|
|
280
|
+
"""
|
|
281
|
+
return month_from_index(int(month) - 1)
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""Read and write dictionaries from and to JSON and CSV files."""
|
|
2
|
+
|
|
3
|
+
import csv
|
|
4
|
+
import json
|
|
5
|
+
from collections.abc import Mapping, Sequence
|
|
6
|
+
from os import PathLike
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
#: Path of a file: a string or a path-like object such as ``pathlib.Path``.
|
|
10
|
+
type StrPath = str | PathLike[str]
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def dict_save_to_json(
|
|
14
|
+
json_filename: StrPath,
|
|
15
|
+
dict_data: object,
|
|
16
|
+
*,
|
|
17
|
+
sort_keys: bool = False,
|
|
18
|
+
indent: int = 4,
|
|
19
|
+
) -> None:
|
|
20
|
+
"""
|
|
21
|
+
Save data to a JSON file.
|
|
22
|
+
|
|
23
|
+
:param json_filename: File path (replaced if it exists).
|
|
24
|
+
:param dict_data: Data to save (dictionaries, lists, etc.).
|
|
25
|
+
:param sort_keys: Sort the dictionary keys (keyword-only).
|
|
26
|
+
:param indent: Indentation spaces (keyword-only).
|
|
27
|
+
"""
|
|
28
|
+
json_data = json.dumps(dict_data, sort_keys=sort_keys, indent=indent)
|
|
29
|
+
Path(json_filename).write_text(json_data, encoding='utf-8')
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def dict_save_to_csv(
|
|
33
|
+
csv_filename: StrPath,
|
|
34
|
+
dict_data: Sequence[Mapping[str, object]],
|
|
35
|
+
delimiter: str = ';',
|
|
36
|
+
) -> None:
|
|
37
|
+
"""
|
|
38
|
+
Save a list of dictionaries to a CSV file.
|
|
39
|
+
|
|
40
|
+
The headers are the keys of the first dictionary. Without data, the file
|
|
41
|
+
is left empty.
|
|
42
|
+
|
|
43
|
+
:param csv_filename: File path (replaced if it exists).
|
|
44
|
+
:param dict_data: Rows, one per dictionary.
|
|
45
|
+
:param delimiter: Column separator.
|
|
46
|
+
"""
|
|
47
|
+
path = Path(csv_filename)
|
|
48
|
+
if len(dict_data) > 0:
|
|
49
|
+
keys = dict_data[0].keys()
|
|
50
|
+
with path.open('w', newline='', encoding='utf-8') as output_file:
|
|
51
|
+
dict_writer = csv.DictWriter(
|
|
52
|
+
output_file, fieldnames=list(keys), delimiter=delimiter
|
|
53
|
+
)
|
|
54
|
+
dict_writer.writeheader()
|
|
55
|
+
dict_writer.writerows(dict_data)
|
|
56
|
+
else:
|
|
57
|
+
path.write_text('', encoding='utf-8')
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def dict_load_from_csv(
|
|
61
|
+
csv_filename: StrPath, delimiter: str = ';'
|
|
62
|
+
) -> list[dict[str, str]]:
|
|
63
|
+
"""
|
|
64
|
+
Read a CSV file as a list of dictionaries.
|
|
65
|
+
|
|
66
|
+
The first row holds the headers, which are used as keys.
|
|
67
|
+
|
|
68
|
+
:param csv_filename: File path.
|
|
69
|
+
:param delimiter: Column separator.
|
|
70
|
+
:return: Rows, one per dictionary.
|
|
71
|
+
:rtype: list[dict[str, str]]
|
|
72
|
+
"""
|
|
73
|
+
with Path(csv_filename).open(newline='', encoding='utf-8') as input_file:
|
|
74
|
+
return list(csv.DictReader(input_file, delimiter=delimiter))
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Recursive merge of dictionaries."""
|
|
2
|
+
|
|
3
|
+
from typing import TypeIs
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def _is_dict(value: object) -> TypeIs[dict[object, object]]:
|
|
7
|
+
"""
|
|
8
|
+
Tell whether a value is a dictionary.
|
|
9
|
+
|
|
10
|
+
:param value: Value to check.
|
|
11
|
+
:return: True if it is a ``dict``.
|
|
12
|
+
:rtype: bool
|
|
13
|
+
"""
|
|
14
|
+
return isinstance(value, dict)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def merge[K, V](
|
|
18
|
+
dictionary_a: dict[K, V],
|
|
19
|
+
dictionary_b: dict[K, V],
|
|
20
|
+
path: list[str] | None = None,
|
|
21
|
+
) -> dict[K, V]:
|
|
22
|
+
"""
|
|
23
|
+
Merge ``dictionary_b`` into ``dictionary_a``.
|
|
24
|
+
|
|
25
|
+
The keys of ``dictionary_b`` are added to ``dictionary_a``. If a key is
|
|
26
|
+
in both and both values are dictionaries, they are merged the same way;
|
|
27
|
+
otherwise, the value of ``dictionary_b`` wins (lists are replaced, not
|
|
28
|
+
joined).
|
|
29
|
+
|
|
30
|
+
:param dictionary_a: Dictionary that is modified.
|
|
31
|
+
:param dictionary_b: Dictionary with the values to add.
|
|
32
|
+
:param path: Keys walked down to this level (internal use).
|
|
33
|
+
:return: The modified ``dictionary_a``.
|
|
34
|
+
:rtype: dict
|
|
35
|
+
"""
|
|
36
|
+
if path is None:
|
|
37
|
+
path = []
|
|
38
|
+
for key, value_b in dictionary_b.items():
|
|
39
|
+
if key in dictionary_a:
|
|
40
|
+
value_a = dictionary_a[key]
|
|
41
|
+
if _is_dict(value_a) and _is_dict(value_b):
|
|
42
|
+
merge(value_a, value_b, [*path, str(key)])
|
|
43
|
+
elif value_a != value_b:
|
|
44
|
+
dictionary_a[key] = value_b
|
|
45
|
+
else:
|
|
46
|
+
dictionary_a[key] = value_b
|
|
47
|
+
return dictionary_a
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""Data encoding functions."""
|
|
2
|
+
|
|
3
|
+
import base64
|
|
4
|
+
import re
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def base64_decode(data: bytes, altchars: bytes = b'+/') -> bytes:
|
|
8
|
+
"""
|
|
9
|
+
Decode base64 data, with optional padding (``=``).
|
|
10
|
+
|
|
11
|
+
Before decoding, characters that are not base64 (for example, line
|
|
12
|
+
breaks) are removed and any missing padding is added.
|
|
13
|
+
Based on https://stackoverflow.com/a/9807138.
|
|
14
|
+
|
|
15
|
+
:param data: Base64 data (ASCII text as bytes).
|
|
16
|
+
:param altchars: The two characters used instead of ``+`` and ``/``.
|
|
17
|
+
:return: Decoded data.
|
|
18
|
+
:rtype: bytes
|
|
19
|
+
"""
|
|
20
|
+
data = re.sub(rb'[^a-zA-Z0-9%s]+' % altchars, b'', data)
|
|
21
|
+
missing_padding = len(data) % 4
|
|
22
|
+
if missing_padding:
|
|
23
|
+
data += b'=' * (4 - missing_padding)
|
|
24
|
+
return base64.b64decode(data, altchars)
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Exceptions shared by several modules of the library."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class NotIndexableError(TypeError):
|
|
5
|
+
|
|
6
|
+
"""
|
|
7
|
+
A value along a key path cannot be indexed with a key.
|
|
8
|
+
|
|
9
|
+
Raised by ``is_empty()`` and ``is_set()``. It is the ``TypeError``
|
|
10
|
+
previously raised when indexing, for example, a string or a number.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
def __init__(self, value_type: type) -> None:
|
|
14
|
+
"""
|
|
15
|
+
Create the error with the type of the value.
|
|
16
|
+
|
|
17
|
+
:param value_type: Type of the value that cannot be indexed.
|
|
18
|
+
"""
|
|
19
|
+
super().__init__(
|
|
20
|
+
f"'{value_type.__name__}' object cannot be indexed with a key"
|
|
21
|
+
)
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Gravatar avatar from an email address."""
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def email_md5(email: str) -> str:
|
|
7
|
+
"""
|
|
8
|
+
Return the MD5 hash of an email address, as used by Gravatar.
|
|
9
|
+
|
|
10
|
+
MD5 is not used for security: it is the identifier Gravatar requires.
|
|
11
|
+
|
|
12
|
+
:param email: Email address.
|
|
13
|
+
:return: MD5 hash in hexadecimal.
|
|
14
|
+
:rtype: str
|
|
15
|
+
"""
|
|
16
|
+
return hashlib.md5(
|
|
17
|
+
email.encode('utf-8'), usedforsecurity=False
|
|
18
|
+
).hexdigest()
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def gravatar_url(email: str) -> str:
|
|
22
|
+
"""
|
|
23
|
+
Return the URL of the Gravatar image of an email address.
|
|
24
|
+
|
|
25
|
+
:param email: Email address.
|
|
26
|
+
:return: Image URL.
|
|
27
|
+
:rtype: str
|
|
28
|
+
"""
|
|
29
|
+
return 'https://gravatar.com/avatar/' + email_md5(email)
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""Check for "empty" values using rules per data type."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Mapping
|
|
4
|
+
from typing import TypeIs
|
|
5
|
+
|
|
6
|
+
from derafu_support.exceptions import NotIndexableError
|
|
7
|
+
|
|
8
|
+
__all__ = ['NotIndexableError', 'UnsupportedTypeError', 'is_empty']
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class UnsupportedTypeError(AttributeError):
|
|
12
|
+
|
|
13
|
+
"""
|
|
14
|
+
Data type that ``is_empty()`` cannot check.
|
|
15
|
+
|
|
16
|
+
It inherits from ``AttributeError``, the exception previously raised in
|
|
17
|
+
this case, so as not to break code that already catches it.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
def __init__(self, value_type: type) -> None:
|
|
21
|
+
"""
|
|
22
|
+
Create the error with the unsupported type.
|
|
23
|
+
|
|
24
|
+
:param value_type: Type of the value received.
|
|
25
|
+
"""
|
|
26
|
+
super().__init__(
|
|
27
|
+
'Unsupported data type for is_empty(): ' + str(value_type)
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _is_mapping(value: object) -> TypeIs[Mapping[object, object]]:
|
|
32
|
+
"""
|
|
33
|
+
Tell whether a value is a dictionary.
|
|
34
|
+
|
|
35
|
+
:param value: Value to check.
|
|
36
|
+
:return: True if it is a ``dict``.
|
|
37
|
+
:rtype: bool
|
|
38
|
+
"""
|
|
39
|
+
return isinstance(value, dict)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _is_collection(
|
|
43
|
+
value: object,
|
|
44
|
+
) -> TypeIs[list[object] | tuple[object, ...] | set[object]]:
|
|
45
|
+
"""
|
|
46
|
+
Tell whether a value is a list, a tuple or a set.
|
|
47
|
+
|
|
48
|
+
:param value: Value to check.
|
|
49
|
+
:return: True if it is a ``list``, ``tuple`` or ``set``.
|
|
50
|
+
:rtype: bool
|
|
51
|
+
"""
|
|
52
|
+
return isinstance(value, list | tuple | set)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _is_empty_dict(var: Mapping[object, object], key: str | None) -> bool:
|
|
56
|
+
"""
|
|
57
|
+
Tell whether a dictionary, or the value of one of its keys, is empty.
|
|
58
|
+
|
|
59
|
+
:param var: Dictionary to check.
|
|
60
|
+
:param key: Key (or ``a.b.c`` path) to check; if None, it checks that
|
|
61
|
+
the dictionary has keys.
|
|
62
|
+
:return: True if it is empty, or if the key does not exist or its value
|
|
63
|
+
is empty.
|
|
64
|
+
:rtype: bool
|
|
65
|
+
"""
|
|
66
|
+
# without a specific key, check that the dictionary has something
|
|
67
|
+
if key is None:
|
|
68
|
+
return len(var) == 0
|
|
69
|
+
# look up the final value of the variable following the given key
|
|
70
|
+
value: object = var
|
|
71
|
+
for k in key.split('.'):
|
|
72
|
+
if not _is_mapping(value):
|
|
73
|
+
# in a list, tuple, set or string without the key, the key does
|
|
74
|
+
# not exist; otherwise the key cannot be looked up
|
|
75
|
+
if (_is_collection(value) or isinstance(value, str)) and (
|
|
76
|
+
k not in value
|
|
77
|
+
):
|
|
78
|
+
return True
|
|
79
|
+
raise NotIndexableError(type(value))
|
|
80
|
+
if k not in value:
|
|
81
|
+
return True
|
|
82
|
+
value = value[k]
|
|
83
|
+
# the key exists in the dictionary: check whether its value is non-empty
|
|
84
|
+
return is_empty(value)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def is_empty(var: object, key: str | None = None) -> bool:
|
|
88
|
+
"""
|
|
89
|
+
Tell whether a variable is "empty", with rules based on its type.
|
|
90
|
+
|
|
91
|
+
- ``None``: always empty.
|
|
92
|
+
- Dictionaries: no keys; or, if ``key`` is given, the key does not exist
|
|
93
|
+
or its value is empty. ``key`` can be a path (``a.b.c``).
|
|
94
|
+
- Lists, tuples and sets: length 0.
|
|
95
|
+
- Strings: ``''``, ``'0'`` or ``'0.0'``.
|
|
96
|
+
- Integers and floats: 0. ``False`` counts as 0 (``bool`` is an
|
|
97
|
+
``int``).
|
|
98
|
+
|
|
99
|
+
:param var: Variable to check.
|
|
100
|
+
:param key: Key (or path of keys) to check if ``var`` is a dictionary.
|
|
101
|
+
:return: True if the variable is empty according to the rules above.
|
|
102
|
+
:rtype: bool
|
|
103
|
+
:raises UnsupportedTypeError: If the type of ``var`` is not one of the
|
|
104
|
+
above.
|
|
105
|
+
:raises NotIndexableError: If the ``key`` path goes through a value that
|
|
106
|
+
is not a dictionary and the key cannot be looked up in it.
|
|
107
|
+
"""
|
|
108
|
+
# if the variable is None the rest is not checked because it is empty
|
|
109
|
+
if var is None:
|
|
110
|
+
return True
|
|
111
|
+
# dictionaries
|
|
112
|
+
if _is_mapping(var):
|
|
113
|
+
return _is_empty_dict(var, key)
|
|
114
|
+
# lists, tuples and sets
|
|
115
|
+
if _is_collection(var):
|
|
116
|
+
return len(var) == 0
|
|
117
|
+
# strings
|
|
118
|
+
if isinstance(var, str):
|
|
119
|
+
return var in {'0', '0.0', ''}
|
|
120
|
+
# integers (including bool) and floats
|
|
121
|
+
if isinstance(var, int | float):
|
|
122
|
+
return var == 0
|
|
123
|
+
# data type not supported for the emptiness check
|
|
124
|
+
raise UnsupportedTypeError(type(var))
|
derafu_support/is_set.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""Check for keys (or key paths) defined in a dictionary."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Mapping
|
|
4
|
+
from typing import TypeIs
|
|
5
|
+
|
|
6
|
+
from derafu_support.exceptions import NotIndexableError
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
'IsSetArgumentError',
|
|
10
|
+
'KeysRequiredError',
|
|
11
|
+
'NotADictionaryError',
|
|
12
|
+
'NotIndexableError',
|
|
13
|
+
'is_set',
|
|
14
|
+
]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class IsSetArgumentError(AttributeError):
|
|
18
|
+
|
|
19
|
+
"""
|
|
20
|
+
Invalid argument for ``is_set()``.
|
|
21
|
+
|
|
22
|
+
It inherits from ``AttributeError``, the exception previously raised in
|
|
23
|
+
these cases, so as not to break code that already catches it.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class NotADictionaryError(IsSetArgumentError):
|
|
28
|
+
|
|
29
|
+
"""The value given to ``is_set()`` is not a dictionary."""
|
|
30
|
+
|
|
31
|
+
def __init__(self) -> None:
|
|
32
|
+
"""Create the error with its message."""
|
|
33
|
+
super().__init__('A dictionary was expected')
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class KeysRequiredError(IsSetArgumentError):
|
|
37
|
+
|
|
38
|
+
"""No keys were given to ``is_set()``."""
|
|
39
|
+
|
|
40
|
+
def __init__(self) -> None:
|
|
41
|
+
"""Create the error with its message."""
|
|
42
|
+
super().__init__('The dictionary keys must be given')
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _is_dict(value: object) -> TypeIs[dict[object, object]]:
|
|
46
|
+
"""
|
|
47
|
+
Tell whether a value is a ``dict``.
|
|
48
|
+
|
|
49
|
+
:param value: Value to check.
|
|
50
|
+
:return: True if it is a ``dict``.
|
|
51
|
+
:rtype: bool
|
|
52
|
+
"""
|
|
53
|
+
return isinstance(value, dict)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _is_mapping(value: object) -> TypeIs[Mapping[object, object]]:
|
|
57
|
+
"""
|
|
58
|
+
Tell whether a value is a dictionary (or a mapping).
|
|
59
|
+
|
|
60
|
+
:param value: Value to check.
|
|
61
|
+
:return: True if it is a ``Mapping``.
|
|
62
|
+
:rtype: bool
|
|
63
|
+
"""
|
|
64
|
+
return isinstance(value, Mapping)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def is_set(var: object, keys: str | None = None) -> bool:
|
|
68
|
+
"""
|
|
69
|
+
Tell whether a key (or ``a.b.c`` path) exists and is not ``None``.
|
|
70
|
+
|
|
71
|
+
:param var: Dictionary to search.
|
|
72
|
+
:param keys: Key, or path of keys separated by dots.
|
|
73
|
+
:return: True if the whole path exists and its value is not ``None``.
|
|
74
|
+
:rtype: bool
|
|
75
|
+
:raises NotADictionaryError: If ``var`` is not a dictionary.
|
|
76
|
+
:raises KeysRequiredError: If no keys are given.
|
|
77
|
+
:raises NotIndexableError: If an intermediate value of the path is not a
|
|
78
|
+
dictionary (for example, a string or a number).
|
|
79
|
+
"""
|
|
80
|
+
if not _is_dict(var):
|
|
81
|
+
raise NotADictionaryError
|
|
82
|
+
if keys is None:
|
|
83
|
+
raise KeysRequiredError
|
|
84
|
+
var_search: object = var
|
|
85
|
+
for key in keys.split('.'):
|
|
86
|
+
if not _is_mapping(var_search):
|
|
87
|
+
raise NotIndexableError(type(var_search))
|
|
88
|
+
try:
|
|
89
|
+
var_search = var_search[key]
|
|
90
|
+
except KeyError:
|
|
91
|
+
return False
|
|
92
|
+
if var_search is None:
|
|
93
|
+
return False
|
|
94
|
+
return True
|
derafu_support/log.py
ADDED
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
"""In-memory message log."""
|
|
2
|
+
|
|
3
|
+
import inspect
|
|
4
|
+
from collections.abc import Mapping
|
|
5
|
+
from datetime import datetime
|
|
6
|
+
from types import FrameType
|
|
7
|
+
from typing import ClassVar, Literal, overload, override
|
|
8
|
+
|
|
9
|
+
_LEVEL_NAMES = {
|
|
10
|
+
10: 'DEBUG',
|
|
11
|
+
20: 'INFO',
|
|
12
|
+
30: 'WARNING',
|
|
13
|
+
40: 'ERROR',
|
|
14
|
+
50: 'CRITICAL',
|
|
15
|
+
}
|
|
16
|
+
# stack levels between the real caller and LogMessage.__init__: the
|
|
17
|
+
# MemoryLogging method that logs (debug, info, ...) and __write
|
|
18
|
+
_INTERNAL_STACK_LEVELS = 2
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class LogMessage:
|
|
22
|
+
|
|
23
|
+
"""Log message, with data about who logged it."""
|
|
24
|
+
|
|
25
|
+
log_format: ClassVar[str] = (
|
|
26
|
+
'%(created)s %(category)s %(level_name)s: %(message)s '
|
|
27
|
+
'[%(module)s:%(line_number)s]'
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
def __init__(
|
|
31
|
+
self,
|
|
32
|
+
level: int,
|
|
33
|
+
message: str,
|
|
34
|
+
args: Mapping[str, object] | None = None,
|
|
35
|
+
category: str | None = None,
|
|
36
|
+
data: object = None,
|
|
37
|
+
caller_level: int | None = None,
|
|
38
|
+
) -> None:
|
|
39
|
+
"""
|
|
40
|
+
Create the message and record the caller's module, file and line.
|
|
41
|
+
|
|
42
|
+
:param level: Message level (10 DEBUG to 50 CRITICAL).
|
|
43
|
+
:param message: Message text.
|
|
44
|
+
:param args: Arguments associated with the message.
|
|
45
|
+
:param category: Category; ``general`` by default.
|
|
46
|
+
:param data: Additional data.
|
|
47
|
+
:param caller_level: How many stack levels to go up to reach the
|
|
48
|
+
caller; 1 by default (whoever called the log method).
|
|
49
|
+
"""
|
|
50
|
+
caller_level = (
|
|
51
|
+
1 if caller_level is None else int(caller_level)
|
|
52
|
+
) + _INTERNAL_STACK_LEVELS
|
|
53
|
+
# log message data
|
|
54
|
+
self.created = (
|
|
55
|
+
datetime.now().astimezone().strftime('%Y-%m-%d %H:%M:%S')
|
|
56
|
+
)
|
|
57
|
+
self.category = category if category is not None else 'general'
|
|
58
|
+
self.level = level
|
|
59
|
+
self.message = message
|
|
60
|
+
self.args = args
|
|
61
|
+
self.data = data
|
|
62
|
+
# add the data of whoever called the log
|
|
63
|
+
caller_frame = self._get_caller_frame(caller_level)
|
|
64
|
+
frame_info = inspect.getframeinfo(caller_frame)
|
|
65
|
+
caller_module = inspect.getmodule(caller_frame)
|
|
66
|
+
# without a module (for example, code run with exec) the frame's
|
|
67
|
+
# module name is used
|
|
68
|
+
self.module: str = (
|
|
69
|
+
caller_module.__name__
|
|
70
|
+
if caller_module is not None
|
|
71
|
+
else str(caller_frame.f_globals.get('__name__', ''))
|
|
72
|
+
)
|
|
73
|
+
self.filename = frame_info.filename
|
|
74
|
+
self.line_number = frame_info.lineno
|
|
75
|
+
self.function_name = frame_info.function
|
|
76
|
+
|
|
77
|
+
@property
|
|
78
|
+
def level_name(self) -> str:
|
|
79
|
+
"""
|
|
80
|
+
Name of the message level.
|
|
81
|
+
|
|
82
|
+
:return: Level name (``DEBUG``, ``INFO``, etc.).
|
|
83
|
+
:rtype: str
|
|
84
|
+
:raises KeyError: If the level is not a standard one.
|
|
85
|
+
"""
|
|
86
|
+
return _LEVEL_NAMES[int(self.level)]
|
|
87
|
+
|
|
88
|
+
@override
|
|
89
|
+
def __str__(self) -> str:
|
|
90
|
+
"""
|
|
91
|
+
Return the message in the log format.
|
|
92
|
+
|
|
93
|
+
:return: Message formatted with ``log_format``.
|
|
94
|
+
:rtype: str
|
|
95
|
+
"""
|
|
96
|
+
return self.log_format % self.to_dict()
|
|
97
|
+
|
|
98
|
+
def to_dict(self) -> dict[str, object]:
|
|
99
|
+
"""
|
|
100
|
+
Return the message data.
|
|
101
|
+
|
|
102
|
+
:return: Data of the message and of who logged it.
|
|
103
|
+
:rtype: dict[str, object]
|
|
104
|
+
"""
|
|
105
|
+
return {
|
|
106
|
+
'created': self.created,
|
|
107
|
+
'category': self.category,
|
|
108
|
+
'level': self.level,
|
|
109
|
+
'level_name': self.level_name,
|
|
110
|
+
'message': self.message,
|
|
111
|
+
'args': self.args,
|
|
112
|
+
'data': self.data,
|
|
113
|
+
'module': self.module,
|
|
114
|
+
'filename': self.filename,
|
|
115
|
+
'line_number': self.line_number,
|
|
116
|
+
'function_name': self.function_name,
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
@staticmethod
|
|
120
|
+
def _get_caller_frame(caller_level: int | None = None) -> FrameType:
|
|
121
|
+
"""
|
|
122
|
+
Get the caller's frame N levels up the stack.
|
|
123
|
+
|
|
124
|
+
If the stack is shorter, the last available frame is returned.
|
|
125
|
+
|
|
126
|
+
:param caller_level: Levels to go up the stack.
|
|
127
|
+
:return: Caller's frame.
|
|
128
|
+
:rtype: FrameType
|
|
129
|
+
:raises RuntimeError: If the interpreter does not allow reading the
|
|
130
|
+
stack.
|
|
131
|
+
"""
|
|
132
|
+
caller_level = (0 if caller_level is None else caller_level) + 1
|
|
133
|
+
caller_frame = inspect.currentframe()
|
|
134
|
+
if caller_frame is None:
|
|
135
|
+
# only happens in interpreters without frame support
|
|
136
|
+
msg = 'The interpreter does not allow reading the call stack'
|
|
137
|
+
raise RuntimeError(msg)
|
|
138
|
+
for _ in range(caller_level):
|
|
139
|
+
if caller_frame.f_back is None:
|
|
140
|
+
break
|
|
141
|
+
caller_frame = caller_frame.f_back
|
|
142
|
+
return caller_frame
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
class MemoryLogging:
|
|
146
|
+
|
|
147
|
+
"""Log that keeps the messages in memory, in a list."""
|
|
148
|
+
|
|
149
|
+
# message severity levels, from lowest to highest
|
|
150
|
+
DEBUG: ClassVar[int] = 10
|
|
151
|
+
INFO: ClassVar[int] = 20
|
|
152
|
+
WARNING: ClassVar[int] = 30
|
|
153
|
+
ERROR: ClassVar[int] = 40
|
|
154
|
+
CRITICAL: ClassVar[int] = 50
|
|
155
|
+
|
|
156
|
+
def __init__(
|
|
157
|
+
self,
|
|
158
|
+
level: int | None = None,
|
|
159
|
+
category: str | None = None,
|
|
160
|
+
caller_level: int | None = None,
|
|
161
|
+
) -> None:
|
|
162
|
+
"""
|
|
163
|
+
Create the empty log.
|
|
164
|
+
|
|
165
|
+
:param level: Minimum level that is kept; ``INFO`` by default.
|
|
166
|
+
:param category: Default category of the messages.
|
|
167
|
+
:param caller_level: Default stack levels used to identify the
|
|
168
|
+
caller.
|
|
169
|
+
"""
|
|
170
|
+
self.__logs: list[LogMessage] = []
|
|
171
|
+
self.logging_level = level if level is not None else MemoryLogging.INFO
|
|
172
|
+
self.default_category = category
|
|
173
|
+
self.caller_level = caller_level
|
|
174
|
+
|
|
175
|
+
def __write(
|
|
176
|
+
self,
|
|
177
|
+
level: int,
|
|
178
|
+
message: str,
|
|
179
|
+
args: Mapping[str, object] | None,
|
|
180
|
+
category: str | None,
|
|
181
|
+
data: object,
|
|
182
|
+
caller_level: int | None,
|
|
183
|
+
) -> LogMessage:
|
|
184
|
+
"""
|
|
185
|
+
Create a message and keep it if it reaches the minimum level.
|
|
186
|
+
|
|
187
|
+
:param level: Message level.
|
|
188
|
+
:param message: Message text.
|
|
189
|
+
:param args: Arguments associated with the message.
|
|
190
|
+
:param category: Category; if None, the default one is used.
|
|
191
|
+
:param data: Additional data.
|
|
192
|
+
:param caller_level: Stack levels; if None, the default is used.
|
|
193
|
+
:return: Created message (whether it is kept or not).
|
|
194
|
+
:rtype: LogMessage
|
|
195
|
+
"""
|
|
196
|
+
if category is None:
|
|
197
|
+
category = self.default_category
|
|
198
|
+
caller_level = (
|
|
199
|
+
caller_level if caller_level is not None else self.caller_level
|
|
200
|
+
)
|
|
201
|
+
log_message = LogMessage(
|
|
202
|
+
level, message, args, category, data, caller_level
|
|
203
|
+
)
|
|
204
|
+
if level >= self.logging_level:
|
|
205
|
+
self.__logs.append(log_message)
|
|
206
|
+
return log_message
|
|
207
|
+
|
|
208
|
+
def debug(
|
|
209
|
+
self,
|
|
210
|
+
message: str,
|
|
211
|
+
args: Mapping[str, object] | None = None,
|
|
212
|
+
category: str | None = None,
|
|
213
|
+
data: object = None,
|
|
214
|
+
caller_level: int | None = None,
|
|
215
|
+
) -> LogMessage:
|
|
216
|
+
"""
|
|
217
|
+
Log a DEBUG level message.
|
|
218
|
+
|
|
219
|
+
:param message: Message text.
|
|
220
|
+
:param args: Arguments associated with the message.
|
|
221
|
+
:param category: Message category.
|
|
222
|
+
:param data: Additional data.
|
|
223
|
+
:param caller_level: Stack levels used to identify the caller.
|
|
224
|
+
:return: Created message.
|
|
225
|
+
:rtype: LogMessage
|
|
226
|
+
"""
|
|
227
|
+
return self.__write(
|
|
228
|
+
MemoryLogging.DEBUG, message, args, category, data, caller_level
|
|
229
|
+
)
|
|
230
|
+
|
|
231
|
+
def info(
|
|
232
|
+
self,
|
|
233
|
+
message: str,
|
|
234
|
+
args: Mapping[str, object] | None = None,
|
|
235
|
+
category: str | None = None,
|
|
236
|
+
data: object = None,
|
|
237
|
+
caller_level: int | None = None,
|
|
238
|
+
) -> LogMessage:
|
|
239
|
+
"""
|
|
240
|
+
Log a INFO level message.
|
|
241
|
+
|
|
242
|
+
:param message: Message text.
|
|
243
|
+
:param args: Arguments associated with the message.
|
|
244
|
+
:param category: Message category.
|
|
245
|
+
:param data: Additional data.
|
|
246
|
+
:param caller_level: Stack levels used to identify the caller.
|
|
247
|
+
:return: Created message.
|
|
248
|
+
:rtype: LogMessage
|
|
249
|
+
"""
|
|
250
|
+
return self.__write(
|
|
251
|
+
MemoryLogging.INFO, message, args, category, data, caller_level
|
|
252
|
+
)
|
|
253
|
+
|
|
254
|
+
def warning(
|
|
255
|
+
self,
|
|
256
|
+
message: str,
|
|
257
|
+
args: Mapping[str, object] | None = None,
|
|
258
|
+
category: str | None = None,
|
|
259
|
+
data: object = None,
|
|
260
|
+
caller_level: int | None = None,
|
|
261
|
+
) -> LogMessage:
|
|
262
|
+
"""
|
|
263
|
+
Log a WARNING level message.
|
|
264
|
+
|
|
265
|
+
:param message: Message text.
|
|
266
|
+
:param args: Arguments associated with the message.
|
|
267
|
+
:param category: Message category.
|
|
268
|
+
:param data: Additional data.
|
|
269
|
+
:param caller_level: Stack levels used to identify the caller.
|
|
270
|
+
:return: Created message.
|
|
271
|
+
:rtype: LogMessage
|
|
272
|
+
"""
|
|
273
|
+
return self.__write(
|
|
274
|
+
MemoryLogging.WARNING, message, args, category, data, caller_level
|
|
275
|
+
)
|
|
276
|
+
|
|
277
|
+
def error(
|
|
278
|
+
self,
|
|
279
|
+
message: str,
|
|
280
|
+
args: Mapping[str, object] | None = None,
|
|
281
|
+
category: str | None = None,
|
|
282
|
+
data: object = None,
|
|
283
|
+
caller_level: int | None = None,
|
|
284
|
+
) -> LogMessage:
|
|
285
|
+
"""
|
|
286
|
+
Log a ERROR level message.
|
|
287
|
+
|
|
288
|
+
:param message: Message text.
|
|
289
|
+
:param args: Arguments associated with the message.
|
|
290
|
+
:param category: Message category.
|
|
291
|
+
:param data: Additional data.
|
|
292
|
+
:param caller_level: Stack levels used to identify the caller.
|
|
293
|
+
:return: Created message.
|
|
294
|
+
:rtype: LogMessage
|
|
295
|
+
"""
|
|
296
|
+
return self.__write(
|
|
297
|
+
MemoryLogging.ERROR, message, args, category, data, caller_level
|
|
298
|
+
)
|
|
299
|
+
|
|
300
|
+
def critical(
|
|
301
|
+
self,
|
|
302
|
+
message: str,
|
|
303
|
+
args: Mapping[str, object] | None = None,
|
|
304
|
+
category: str | None = None,
|
|
305
|
+
data: object = None,
|
|
306
|
+
caller_level: int | None = None,
|
|
307
|
+
) -> LogMessage:
|
|
308
|
+
"""
|
|
309
|
+
Log a CRITICAL level message.
|
|
310
|
+
|
|
311
|
+
:param message: Message text.
|
|
312
|
+
:param args: Arguments associated with the message.
|
|
313
|
+
:param category: Message category.
|
|
314
|
+
:param data: Additional data.
|
|
315
|
+
:param caller_level: Stack levels used to identify the caller.
|
|
316
|
+
:return: Created message.
|
|
317
|
+
:rtype: LogMessage
|
|
318
|
+
"""
|
|
319
|
+
return self.__write(
|
|
320
|
+
MemoryLogging.CRITICAL, message, args, category, data, caller_level
|
|
321
|
+
)
|
|
322
|
+
|
|
323
|
+
@overload
|
|
324
|
+
def get_all(
|
|
325
|
+
self, *, as_dict: Literal[False] = False
|
|
326
|
+
) -> list[LogMessage]: ...
|
|
327
|
+
|
|
328
|
+
@overload
|
|
329
|
+
def get_all(
|
|
330
|
+
self, *, as_dict: Literal[True]
|
|
331
|
+
) -> list[dict[str, object]]: ...
|
|
332
|
+
|
|
333
|
+
def get_all(
|
|
334
|
+
self, *, as_dict: bool = False
|
|
335
|
+
) -> list[LogMessage] | list[dict[str, object]]:
|
|
336
|
+
"""
|
|
337
|
+
Return the kept messages.
|
|
338
|
+
|
|
339
|
+
:param as_dict: Return each message as a dictionary
|
|
340
|
+
(``LogMessage.to_dict()``) instead of as a ``LogMessage``
|
|
341
|
+
(keyword-only).
|
|
342
|
+
:return: Messages, from oldest to newest.
|
|
343
|
+
:rtype: list[LogMessage] | list[dict[str, object]]
|
|
344
|
+
"""
|
|
345
|
+
if as_dict:
|
|
346
|
+
return [log.to_dict() for log in self.__logs]
|
|
347
|
+
return self.__logs
|
|
348
|
+
|
|
349
|
+
@overload
|
|
350
|
+
def flush(
|
|
351
|
+
self, *, as_dict: Literal[False] = False
|
|
352
|
+
) -> list[LogMessage]: ...
|
|
353
|
+
|
|
354
|
+
@overload
|
|
355
|
+
def flush(self, *, as_dict: Literal[True]) -> list[dict[str, object]]: ...
|
|
356
|
+
|
|
357
|
+
def flush(
|
|
358
|
+
self, *, as_dict: bool = False
|
|
359
|
+
) -> list[LogMessage] | list[dict[str, object]]:
|
|
360
|
+
"""
|
|
361
|
+
Return the kept messages and empty the log.
|
|
362
|
+
|
|
363
|
+
:param as_dict: Return each message as a dictionary instead of as a
|
|
364
|
+
``LogMessage`` (keyword-only).
|
|
365
|
+
:return: Messages that were in the log.
|
|
366
|
+
:rtype: list[LogMessage] | list[dict[str, object]]
|
|
367
|
+
"""
|
|
368
|
+
logs = (
|
|
369
|
+
[log.to_dict() for log in self.__logs] if as_dict else self.__logs
|
|
370
|
+
)
|
|
371
|
+
self.__logs = []
|
|
372
|
+
return logs
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""Locale-aware number formatting (thousands and decimal separators)."""
|
|
2
|
+
|
|
3
|
+
from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
|
|
4
|
+
|
|
5
|
+
from babel.core import UnknownLocaleError
|
|
6
|
+
from babel.numbers import format_decimal
|
|
7
|
+
|
|
8
|
+
# decimal places when decimals are requested (decimal_digits=True)
|
|
9
|
+
_DEFAULT_DECIMAL_DIGITS = 2
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def format_number(
|
|
13
|
+
value: object, decimal_digits: object = None, locale: str = 'es_CL'
|
|
14
|
+
) -> str:
|
|
15
|
+
"""
|
|
16
|
+
Format a number with the locale's thousands and decimal separators.
|
|
17
|
+
|
|
18
|
+
The number is rounded "half up" (``ROUND_HALF_UP``) to the given number
|
|
19
|
+
of decimal places.
|
|
20
|
+
|
|
21
|
+
:param value: Number (or string with a number) to format. ``None`` is
|
|
22
|
+
shown as ``0``.
|
|
23
|
+
:param decimal_digits: Number of decimal places (integer); ``None`` or
|
|
24
|
+
``False`` is 0 and ``True`` is 2.
|
|
25
|
+
:param locale: Locale, for example ``es_CL`` or ``es-CL``.
|
|
26
|
+
:return: Formatted number. If the value is not a number, the number of
|
|
27
|
+
decimal places is not an integer or is negative, or the locale does
|
|
28
|
+
not exist, the value is returned unformatted.
|
|
29
|
+
:rtype: str
|
|
30
|
+
"""
|
|
31
|
+
if value is None:
|
|
32
|
+
return '0'
|
|
33
|
+
try:
|
|
34
|
+
number = Decimal(str(value))
|
|
35
|
+
except (TypeError, ValueError, InvalidOperation):
|
|
36
|
+
return str(value)
|
|
37
|
+
if decimal_digits is None:
|
|
38
|
+
decimal_digits = 0
|
|
39
|
+
elif decimal_digits is True:
|
|
40
|
+
decimal_digits = _DEFAULT_DECIMAL_DIGITS
|
|
41
|
+
if not isinstance(decimal_digits, int) or decimal_digits < 0:
|
|
42
|
+
return str(number)
|
|
43
|
+
# Babel uses "_" to separate language and country
|
|
44
|
+
locale = locale.replace('-', '_')
|
|
45
|
+
try:
|
|
46
|
+
# round the value with Decimal
|
|
47
|
+
number = number.quantize(
|
|
48
|
+
Decimal('1.' + '0' * decimal_digits), rounding=ROUND_HALF_UP
|
|
49
|
+
)
|
|
50
|
+
format_pattern = '#,##0' + (
|
|
51
|
+
'.' + '0' * decimal_digits if decimal_digits > 0 else ''
|
|
52
|
+
)
|
|
53
|
+
return format_decimal(number, format=format_pattern, locale=locale)
|
|
54
|
+
except (InvalidOperation, ValueError, UnknownLocaleError):
|
|
55
|
+
# formatting error: the value is returned unformatted
|
|
56
|
+
return str(number)
|
derafu_support/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: derafu-support
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: General-purpose Python utilities (dates, dictionaries, numbers and logging).
|
|
5
|
+
Author: Derafu
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Repository, https://github.com/derafu/support-python
|
|
8
|
+
Project-URL: Issues, https://github.com/derafu/support-python/issues
|
|
9
|
+
Keywords: utilities,dates,dictionary,logging,formatting
|
|
10
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
18
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
19
|
+
Classifier: Topic :: Utilities
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Requires-Python: >=3.13
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Requires-Dist: Babel>=2.19
|
|
25
|
+
Dynamic: license-file
|
|
26
|
+
|
|
27
|
+
# derafu-support
|
|
28
|
+
|
|
29
|
+
General-purpose Python utilities. The library does not depend on Django.
|
|
30
|
+
|
|
31
|
+
Requires Python 3.13 or newer; tested on 3.13, 3.14 and 3.15.
|
|
32
|
+
|
|
33
|
+
## Installation
|
|
34
|
+
|
|
35
|
+
```sh
|
|
36
|
+
pip install derafu-support
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Contents
|
|
40
|
+
|
|
41
|
+
| Module | Contents |
|
|
42
|
+
|---|---|
|
|
43
|
+
| `dates` | YYYYMM periods (`period_current`, `period_previous`, `period_next`, `period_range`, `period_first_day`, `period_last_day`, `period_valid`), dates (`date_normalize`, `date_add_days`, `date_count_days`) and Spanish month names (`month_from_string`, `month_from_index`, `month_from_number`) |
|
|
44
|
+
| `dictionary_merge` | `merge()`: recursive merge of dictionaries |
|
|
45
|
+
| `dictionary_file_operations` | `dict_save_to_json()`, `dict_save_to_csv()` and `dict_load_from_csv()` |
|
|
46
|
+
| `is_empty` / `is_set` | Checks for empty values and defined keys |
|
|
47
|
+
| `exceptions` | `NotIndexableError`, raised by both `is_empty()` and `is_set()` |
|
|
48
|
+
| `log` | `MemoryLogging`: in-memory log that records the caller |
|
|
49
|
+
| `number_format` | `format_number()`: locale-aware thousands and decimal separators |
|
|
50
|
+
| `gravatar` | `email_md5()` and `gravatar_url()` |
|
|
51
|
+
| `encoding` | `base64_decode()` with optional padding |
|
|
52
|
+
|
|
53
|
+
Example: `from derafu_support.dates import period_current`.
|
|
54
|
+
|
|
55
|
+
The dictionary selector (`selector()`) lives in the
|
|
56
|
+
[derafu-selector](https://github.com/derafu/selector-python) library.
|
|
57
|
+
|
|
58
|
+
## Development
|
|
59
|
+
|
|
60
|
+
```sh
|
|
61
|
+
make install-dev PYTHON=python3.15 # creates venv/ with the library and tools
|
|
62
|
+
make check # ruff, mypy, pyright and pytest
|
|
63
|
+
make build # builds dist/ and checks it with twine
|
|
64
|
+
make upload # builds dist/ and publishes it on PyPI
|
|
65
|
+
make docs # builds the Sphinx docs in docs/_build/html
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## License
|
|
69
|
+
|
|
70
|
+
MIT. See [LICENSE](https://github.com/derafu/support-python/blob/main/LICENSE).
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
derafu_support/__init__.py,sha256=IpIfxXkBXTOSr7jjcrNxXk0D5lpkRghE88PlzfxaBS8,142
|
|
2
|
+
derafu_support/dates.py,sha256=IaSO8e9XuAWrcz6jU_GwaIJeZuvDQejx_2VHWu457s8,8392
|
|
3
|
+
derafu_support/dictionary_file_operations.py,sha256=GHmLCaCE2oEkMI_EWR2xCEnUL7Fh7RV0LmVNPEQD1L0,2267
|
|
4
|
+
derafu_support/dictionary_merge.py,sha256=3kSPd_4FcNR7B5aSNxPg_nkWBQyYgPmdLh4Ech-QegQ,1422
|
|
5
|
+
derafu_support/encoding.py,sha256=PFk9F99uTOVr_18sWTzCGE78EJ00XhzrvLl69BITkM0,756
|
|
6
|
+
derafu_support/exceptions.py,sha256=LAH9MWcGVZ7Gg5NvyhufAkIqta9U8k4p5_KEdguv22g,626
|
|
7
|
+
derafu_support/gravatar.py,sha256=KwKQuGjOAZZZavumgtHLBigJRn4YMWg7VJfNL7cwZhQ,689
|
|
8
|
+
derafu_support/is_empty.py,sha256=7G47f8ajkHmXLXph_8ZhZ2j6RXvZPhqZzOP5qDCx-Ic,4079
|
|
9
|
+
derafu_support/is_set.py,sha256=KhQ8RD-epR2l9-35GstPuyt1EODw_wYo0zSXennrNyc,2591
|
|
10
|
+
derafu_support/log.py,sha256=6C7Oe_U0E_PAxAUOtetlti0KTg9rHtBaF-skilRKWJo,11820
|
|
11
|
+
derafu_support/number_format.py,sha256=lyHZTWTCMiCV13eMejiARCtjN3WtPeV4wnQg8Zcx0VU,2107
|
|
12
|
+
derafu_support/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
13
|
+
derafu_support-1.0.0.dist-info/licenses/LICENSE,sha256=wkUIn63J2GnKY5NquvcTp0OTryf6HJvoljUWNsOCjeU,1117
|
|
14
|
+
derafu_support-1.0.0.dist-info/METADATA,sha256=Hs4TN80Qp2vUB2kJc7o0qIPwzjkbyQPhwLdjjZI4D2c,2882
|
|
15
|
+
derafu_support-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
16
|
+
derafu_support-1.0.0.dist-info/top_level.txt,sha256=Om8IykTc9Zh9BTx5Aohs43M3pi5AMScXTfF4sIZXdIo,15
|
|
17
|
+
derafu_support-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Esteban De La Fuente Rubio / Derafu <https://www.derafu.org>
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
derafu_support
|