annunciator 1.1.1__tar.gz

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.
Files changed (41) hide show
  1. annunciator-1.1.1/LICENSE +21 -0
  2. annunciator-1.1.1/PKG-INFO +123 -0
  3. annunciator-1.1.1/README.md +94 -0
  4. annunciator-1.1.1/pyproject.toml +53 -0
  5. annunciator-1.1.1/setup.cfg +4 -0
  6. annunciator-1.1.1/src/annunciator/__init__.py +235 -0
  7. annunciator-1.1.1/src/annunciator/__main__.py +8 -0
  8. annunciator-1.1.1/src/annunciator/_coded.py +112 -0
  9. annunciator-1.1.1/src/annunciator/_version.py +3 -0
  10. annunciator-1.1.1/src/annunciator/catalogue.py +979 -0
  11. annunciator-1.1.1/src/annunciator/checks.py +387 -0
  12. annunciator-1.1.1/src/annunciator/cli.py +296 -0
  13. annunciator-1.1.1/src/annunciator/config.py +721 -0
  14. annunciator-1.1.1/src/annunciator/context.py +127 -0
  15. annunciator-1.1.1/src/annunciator/errors.py +226 -0
  16. annunciator-1.1.1/src/annunciator/events.py +423 -0
  17. annunciator-1.1.1/src/annunciator/filters.py +426 -0
  18. annunciator-1.1.1/src/annunciator/formatters.py +245 -0
  19. annunciator-1.1.1/src/annunciator/handlers.py +306 -0
  20. annunciator-1.1.1/src/annunciator/handling.py +860 -0
  21. annunciator-1.1.1/src/annunciator/hooks.py +244 -0
  22. annunciator-1.1.1/src/annunciator/htmlreport.py +433 -0
  23. annunciator-1.1.1/src/annunciator/integrity.py +294 -0
  24. annunciator-1.1.1/src/annunciator/levels.py +159 -0
  25. annunciator-1.1.1/src/annunciator/lint.py +207 -0
  26. annunciator-1.1.1/src/annunciator/logger.py +637 -0
  27. annunciator-1.1.1/src/annunciator/multiprocess.py +154 -0
  28. annunciator-1.1.1/src/annunciator/provenance.py +367 -0
  29. annunciator-1.1.1/src/annunciator/py.typed +0 -0
  30. annunciator-1.1.1/src/annunciator/recorder.py +152 -0
  31. annunciator-1.1.1/src/annunciator/report.py +555 -0
  32. annunciator-1.1.1/src/annunciator/sphinxext.py +145 -0
  33. annunciator-1.1.1/src/annunciator/testing.py +240 -0
  34. annunciator-1.1.1/src/annunciator/warns.py +122 -0
  35. annunciator-1.1.1/src/annunciator/watch.py +355 -0
  36. annunciator-1.1.1/src/annunciator.egg-info/PKG-INFO +123 -0
  37. annunciator-1.1.1/src/annunciator.egg-info/SOURCES.txt +39 -0
  38. annunciator-1.1.1/src/annunciator.egg-info/dependency_links.txt +1 -0
  39. annunciator-1.1.1/src/annunciator.egg-info/entry_points.txt +5 -0
  40. annunciator-1.1.1/src/annunciator.egg-info/requires.txt +9 -0
  41. annunciator-1.1.1/src/annunciator.egg-info/top_level.txt +1 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tom Scott
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,123 @@
1
+ Metadata-Version: 2.4
2
+ Name: annunciator
3
+ Version: 1.1.1
4
+ Summary: Error, warning and information handling and logging with message catalogues.
5
+ Author: Tom Scott
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/MasonicTombomb/annunciator
8
+ Project-URL: Source, https://github.com/MasonicTombomb/annunciator
9
+ Project-URL: Changelog, https://github.com/MasonicTombomb/annunciator/blob/main/CHANGELOG.md
10
+ Project-URL: Issues, https://github.com/MasonicTombomb/annunciator/issues
11
+ Keywords: logging,errors,warnings,exceptions,message catalogue
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Topic :: System :: Logging
19
+ Classifier: Typing :: Typed
20
+ Requires-Python: >=3.9
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Provides-Extra: toml
24
+ Requires-Dist: tomli>=2.0; python_version < "3.11" and extra == "toml"
25
+ Provides-Extra: docs
26
+ Requires-Dist: sphinx>=7.2; extra == "docs"
27
+ Requires-Dist: furo>=2024.1; extra == "docs"
28
+ Dynamic: license-file
29
+
30
+ # annunciator
31
+
32
+ Error, warning and information handling and logging for Python.
33
+
34
+ `annunciator` uses only the Python standard library. It gives you:
35
+
36
+ - structured log records with seven severity levels and context data,
37
+ - message catalogues: each message has a code, a cause and a remedy,
38
+ - coded exceptions and coded warnings,
39
+ - decorators and context managers for error handling (`handle_errors`,
40
+ `guard`, `retry`, `ErrorCollector`, `timed`, `log_calls`, `deprecated`),
41
+ - hooks that record exceptions that no code caught,
42
+ - plain text, colour and JSON Lines output, with file rotation,
43
+ - redaction of secret data, a duplicate filter and a rate limit,
44
+ - reports, CSV export and a command-line interface for log files,
45
+ - a Sphinx directive that writes your message reference,
46
+ - for long runs: a flight recorder, `once`/`every`/`throttle`, progress
47
+ records, stall detection and failure fingerprints,
48
+ - for evidence: run manifests, tamper-evident log files (`annunciator
49
+ verify`) and run comparison (`annunciator diff`),
50
+ - for robust operation: one log writer for many processes, local variables
51
+ in tracebacks and soft checks,
52
+ - for development: `annunciator lint`, a pytest fixture and an HTML report.
53
+
54
+ ## Install
55
+
56
+ Into any Python environment (venv, conda, mamba, pyenv, system):
57
+
58
+ ```console
59
+ python -m pip install annunciator
60
+ ```
61
+
62
+ From GitHub (latest `main`, or a fixed tag):
63
+
64
+ ```console
65
+ python -m pip install "git+https://github.com/MasonicTombomb/annunciator.git"
66
+ python -m pip install "git+https://github.com/MasonicTombomb/annunciator.git@v1.1.1"
67
+ ```
68
+
69
+ With uv: `uv pip install annunciator`. In a conda environment, `pip install`
70
+ as above works; a native conda package is also built for each release
71
+ (`conda install -c MasonicTombomb annunciator` when it is uploaded to
72
+ anaconda.org).
73
+
74
+ From a local clone: `python -m pip install .`
75
+
76
+ Python 3.9 or later is necessary. On Python 3.9 and 3.10, install the extra
77
+ `toml` to read TOML files: `python -m pip install "annunciator[toml]"`.
78
+
79
+ ## Release
80
+
81
+ 1. Set `__version__` in `src/annunciator/_version.py` and add an entry to
82
+ `CHANGELOG.md`.
83
+ 2. Commit, then tag and push: `git tag v1.2.0 && git push origin main v1.2.0`.
84
+
85
+ The workflow `.github/workflows/release.yml` builds the sdist and wheel,
86
+ tests them on Linux, Windows and macOS, publishes to PyPI, creates a GitHub
87
+ release with the files attached and builds a conda package.
88
+
89
+ ## Quick start
90
+
91
+ ```python
92
+ from annunciator import MessageCatalogue, CodedError, configure, get_logger
93
+
94
+ configure(level="INFO", file="logs/run.jsonl", file_format="json")
95
+ log = get_logger(__name__)
96
+
97
+ APP = MessageCatalogue("APP", "Application messages")
98
+ APP.define(1, "E", "The detector '{name}' does not answer.",
99
+ cause="The detector has no power or the cable is not connected.",
100
+ remedy="Make sure that the detector has power. Examine the cable.")
101
+
102
+ log.info("The measurement started.", sample="CeO2-04", live_time=600)
103
+ log.event("APP-E-0001", name="HPGe-2")
104
+ raise CodedError(code="APP-E-0001", name="HPGe-2")
105
+ ```
106
+
107
+ ## Documentation
108
+
109
+ The built user manual (document ANN-UM-001) is in the directory `manual`
110
+ (PDF and HTML). Its source files are in the directory `docs`. Its
111
+ structure follows ISO/IEC/IEEE 26514:2022. Its text follows the writing rules
112
+ of ASD-STE100 Issue 9.
113
+
114
+ ```console
115
+ python -m pip install ".[docs]"
116
+ sphinx-build -b html docs docs/_build/html
117
+ sphinx-build -M latexpdf docs docs/_build
118
+ python tools/ste_check.py docs
119
+ ```
120
+
121
+ ## Licence
122
+
123
+ MIT. Refer to the file `LICENSE`.
@@ -0,0 +1,94 @@
1
+ # annunciator
2
+
3
+ Error, warning and information handling and logging for Python.
4
+
5
+ `annunciator` uses only the Python standard library. It gives you:
6
+
7
+ - structured log records with seven severity levels and context data,
8
+ - message catalogues: each message has a code, a cause and a remedy,
9
+ - coded exceptions and coded warnings,
10
+ - decorators and context managers for error handling (`handle_errors`,
11
+ `guard`, `retry`, `ErrorCollector`, `timed`, `log_calls`, `deprecated`),
12
+ - hooks that record exceptions that no code caught,
13
+ - plain text, colour and JSON Lines output, with file rotation,
14
+ - redaction of secret data, a duplicate filter and a rate limit,
15
+ - reports, CSV export and a command-line interface for log files,
16
+ - a Sphinx directive that writes your message reference,
17
+ - for long runs: a flight recorder, `once`/`every`/`throttle`, progress
18
+ records, stall detection and failure fingerprints,
19
+ - for evidence: run manifests, tamper-evident log files (`annunciator
20
+ verify`) and run comparison (`annunciator diff`),
21
+ - for robust operation: one log writer for many processes, local variables
22
+ in tracebacks and soft checks,
23
+ - for development: `annunciator lint`, a pytest fixture and an HTML report.
24
+
25
+ ## Install
26
+
27
+ Into any Python environment (venv, conda, mamba, pyenv, system):
28
+
29
+ ```console
30
+ python -m pip install annunciator
31
+ ```
32
+
33
+ From GitHub (latest `main`, or a fixed tag):
34
+
35
+ ```console
36
+ python -m pip install "git+https://github.com/MasonicTombomb/annunciator.git"
37
+ python -m pip install "git+https://github.com/MasonicTombomb/annunciator.git@v1.1.1"
38
+ ```
39
+
40
+ With uv: `uv pip install annunciator`. In a conda environment, `pip install`
41
+ as above works; a native conda package is also built for each release
42
+ (`conda install -c MasonicTombomb annunciator` when it is uploaded to
43
+ anaconda.org).
44
+
45
+ From a local clone: `python -m pip install .`
46
+
47
+ Python 3.9 or later is necessary. On Python 3.9 and 3.10, install the extra
48
+ `toml` to read TOML files: `python -m pip install "annunciator[toml]"`.
49
+
50
+ ## Release
51
+
52
+ 1. Set `__version__` in `src/annunciator/_version.py` and add an entry to
53
+ `CHANGELOG.md`.
54
+ 2. Commit, then tag and push: `git tag v1.2.0 && git push origin main v1.2.0`.
55
+
56
+ The workflow `.github/workflows/release.yml` builds the sdist and wheel,
57
+ tests them on Linux, Windows and macOS, publishes to PyPI, creates a GitHub
58
+ release with the files attached and builds a conda package.
59
+
60
+ ## Quick start
61
+
62
+ ```python
63
+ from annunciator import MessageCatalogue, CodedError, configure, get_logger
64
+
65
+ configure(level="INFO", file="logs/run.jsonl", file_format="json")
66
+ log = get_logger(__name__)
67
+
68
+ APP = MessageCatalogue("APP", "Application messages")
69
+ APP.define(1, "E", "The detector '{name}' does not answer.",
70
+ cause="The detector has no power or the cable is not connected.",
71
+ remedy="Make sure that the detector has power. Examine the cable.")
72
+
73
+ log.info("The measurement started.", sample="CeO2-04", live_time=600)
74
+ log.event("APP-E-0001", name="HPGe-2")
75
+ raise CodedError(code="APP-E-0001", name="HPGe-2")
76
+ ```
77
+
78
+ ## Documentation
79
+
80
+ The built user manual (document ANN-UM-001) is in the directory `manual`
81
+ (PDF and HTML). Its source files are in the directory `docs`. Its
82
+ structure follows ISO/IEC/IEEE 26514:2022. Its text follows the writing rules
83
+ of ASD-STE100 Issue 9.
84
+
85
+ ```console
86
+ python -m pip install ".[docs]"
87
+ sphinx-build -b html docs docs/_build/html
88
+ sphinx-build -M latexpdf docs docs/_build
89
+ python tools/ste_check.py docs
90
+ ```
91
+
92
+ ## Licence
93
+
94
+ MIT. Refer to the file `LICENSE`.
@@ -0,0 +1,53 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "annunciator"
7
+ dynamic = ["version"]
8
+ description = "Error, warning and information handling and logging with message catalogues."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Tom Scott" }]
14
+ keywords = ["logging", "errors", "warnings", "exceptions", "message catalogue"]
15
+ classifiers = [
16
+ "Development Status :: 4 - Beta",
17
+ "Intended Audience :: Developers",
18
+ "Intended Audience :: Science/Research",
19
+ "Operating System :: OS Independent",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3 :: Only",
22
+ "Topic :: System :: Logging",
23
+ "Typing :: Typed",
24
+ ]
25
+ dependencies = []
26
+
27
+ [project.urls]
28
+ Homepage = "https://github.com/MasonicTombomb/annunciator"
29
+ Source = "https://github.com/MasonicTombomb/annunciator"
30
+ Changelog = "https://github.com/MasonicTombomb/annunciator/blob/main/CHANGELOG.md"
31
+ Issues = "https://github.com/MasonicTombomb/annunciator/issues"
32
+
33
+ [project.optional-dependencies]
34
+ toml = ["tomli>=2.0; python_version < '3.11'"]
35
+ docs = ["sphinx>=7.2", "furo>=2024.1"]
36
+
37
+ [project.scripts]
38
+ annunciator = "annunciator.cli:main"
39
+
40
+ [project.entry-points.pytest11]
41
+ annunciator = "annunciator.testing"
42
+
43
+ [tool.setuptools]
44
+ package-dir = { "" = "src" }
45
+
46
+ [tool.setuptools.packages.find]
47
+ where = ["src"]
48
+
49
+ [tool.setuptools.package-data]
50
+ annunciator = ["py.typed"]
51
+
52
+ [tool.setuptools.dynamic]
53
+ version = { attr = "annunciator._version.__version__" }
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,235 @@
1
+ """annunciator: error, warning and information handling and logging.
2
+
3
+ The package gives one consistent system for these functions:
4
+
5
+ * structured log records with severity levels and context data,
6
+ * message catalogues with a code, a cause and a remedy for each message,
7
+ * coded exceptions and coded warnings,
8
+ * decorators and context managers for error handling,
9
+ * hooks that record exceptions that no code caught,
10
+ * reports and a command-line interface for log files,
11
+ * a flight recorder, progress records and stall detection for long runs,
12
+ * run manifests and tamper-evident log files,
13
+ * safe logs from many processes, soft checks and tools for tests.
14
+
15
+ The package uses only the Python standard library.
16
+
17
+ Examples
18
+ --------
19
+ >>> import annunciator
20
+ >>> config = annunciator.configure(console=False, install_hooks=False)
21
+ >>> log = annunciator.get_logger("example")
22
+ >>> log.info("The run started.", run=17)
23
+ >>> annunciator.get_store().events[-1].fields
24
+ {'run': 17}
25
+ >>> annunciator.shutdown()
26
+ """
27
+
28
+ from ._version import __version__
29
+ from .catalogue import (
30
+ BUILTIN,
31
+ MessageCatalogue,
32
+ MessageDefinition,
33
+ catalogues,
34
+ explain,
35
+ get_catalogue,
36
+ lookup,
37
+ make_code,
38
+ parse_code,
39
+ register_catalogue,
40
+ unregister_catalogue,
41
+ )
42
+ from .config import (
43
+ LogConfig,
44
+ configure,
45
+ current_config,
46
+ get_store,
47
+ is_configured,
48
+ shutdown,
49
+ )
50
+ from .context import (
51
+ bind,
52
+ clear_context,
53
+ context,
54
+ get_context,
55
+ new_correlation_id,
56
+ unbind,
57
+ )
58
+ from .errors import (
59
+ AggregateError,
60
+ CatalogueError,
61
+ CodedError,
62
+ ConfigurationError,
63
+ DataError,
64
+ DependencyError,
65
+ InternalError,
66
+ OperationError,
67
+ OperationTimeoutError,
68
+ ResourceAccessError,
69
+ ResourceError,
70
+ ResourceNotFoundError,
71
+ RetryExhaustedError,
72
+ ValidationError,
73
+ )
74
+ from .events import Event, ExceptionInfo, SourceLocation
75
+ from .checks import (
76
+ check,
77
+ check_finite,
78
+ check_not_empty,
79
+ check_one_of,
80
+ check_range,
81
+ check_type,
82
+ )
83
+ from .handling import (
84
+ ErrorCollector,
85
+ deprecated,
86
+ guard,
87
+ handle_errors,
88
+ log_calls,
89
+ retry,
90
+ timed,
91
+ )
92
+ from .hooks import (
93
+ hooks_installed,
94
+ install_asyncio_handler,
95
+ install_hooks,
96
+ uninstall_hooks,
97
+ )
98
+ from .integrity import verify_chain
99
+ from .levels import Severity, register_levels
100
+ from .logger import (
101
+ StructuredLogger,
102
+ get_logger,
103
+ record_suppressed_summary,
104
+ reset_occurrences,
105
+ suppressed_counts,
106
+ )
107
+ from .provenance import Run, collect_manifest, start_run
108
+ from .recorder import FlightRecorderHandler
109
+ from .report import (
110
+ EventReport,
111
+ RunComparison,
112
+ compare_runs,
113
+ export_csv,
114
+ read_events,
115
+ select_events,
116
+ summarise,
117
+ write_events,
118
+ )
119
+ from .watch import Progress, Watchdog, track
120
+ from .htmlreport import write_html_report
121
+ from .warns import (
122
+ CodedWarning,
123
+ ConfigurationWarning,
124
+ DataQualityWarning,
125
+ DeprecatedFeatureWarning,
126
+ PerformanceWarning,
127
+ warn,
128
+ )
129
+
130
+ register_levels()
131
+
132
+ __all__ = [
133
+ "__version__",
134
+ # levels
135
+ "Severity",
136
+ "register_levels",
137
+ # catalogue
138
+ "BUILTIN",
139
+ "MessageCatalogue",
140
+ "MessageDefinition",
141
+ "catalogues",
142
+ "explain",
143
+ "get_catalogue",
144
+ "lookup",
145
+ "make_code",
146
+ "parse_code",
147
+ "register_catalogue",
148
+ "unregister_catalogue",
149
+ # configuration
150
+ "LogConfig",
151
+ "configure",
152
+ "current_config",
153
+ "get_store",
154
+ "is_configured",
155
+ "shutdown",
156
+ # context
157
+ "bind",
158
+ "clear_context",
159
+ "context",
160
+ "get_context",
161
+ "new_correlation_id",
162
+ "unbind",
163
+ # errors
164
+ "AggregateError",
165
+ "CatalogueError",
166
+ "CodedError",
167
+ "ConfigurationError",
168
+ "DataError",
169
+ "DependencyError",
170
+ "InternalError",
171
+ "OperationError",
172
+ "OperationTimeoutError",
173
+ "ResourceAccessError",
174
+ "ResourceError",
175
+ "ResourceNotFoundError",
176
+ "RetryExhaustedError",
177
+ "ValidationError",
178
+ # warnings
179
+ "CodedWarning",
180
+ "ConfigurationWarning",
181
+ "DataQualityWarning",
182
+ "DeprecatedFeatureWarning",
183
+ "PerformanceWarning",
184
+ "warn",
185
+ # events
186
+ "Event",
187
+ "ExceptionInfo",
188
+ "SourceLocation",
189
+ # loggers
190
+ "StructuredLogger",
191
+ "get_logger",
192
+ # handling
193
+ "ErrorCollector",
194
+ "deprecated",
195
+ "guard",
196
+ "handle_errors",
197
+ "log_calls",
198
+ "retry",
199
+ "timed",
200
+ # hooks
201
+ "hooks_installed",
202
+ "install_asyncio_handler",
203
+ "install_hooks",
204
+ "uninstall_hooks",
205
+ # reports
206
+ "EventReport",
207
+ "export_csv",
208
+ "read_events",
209
+ "select_events",
210
+ "summarise",
211
+ "write_events",
212
+ "RunComparison",
213
+ "compare_runs",
214
+ "write_html_report",
215
+ # long runs
216
+ "FlightRecorderHandler",
217
+ "Progress",
218
+ "Watchdog",
219
+ "track",
220
+ "record_suppressed_summary",
221
+ "reset_occurrences",
222
+ "suppressed_counts",
223
+ # runs and integrity
224
+ "Run",
225
+ "collect_manifest",
226
+ "start_run",
227
+ "verify_chain",
228
+ # checks
229
+ "check",
230
+ "check_finite",
231
+ "check_not_empty",
232
+ "check_one_of",
233
+ "check_range",
234
+ "check_type",
235
+ ]
@@ -0,0 +1,8 @@
1
+ """Start the command-line interface with ``python -m annunciator``."""
2
+
3
+ import sys
4
+
5
+ from .cli import main
6
+
7
+ if __name__ == "__main__":
8
+ sys.exit(main())
@@ -0,0 +1,112 @@
1
+ """Shared behaviour of coded errors and coded warnings (internal module)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, ClassVar, Dict, Mapping, Optional
6
+
7
+ from .catalogue import lookup
8
+ from .levels import Severity
9
+
10
+
11
+ class CodedMixin:
12
+ """Behaviour that coded errors and coded warnings have in common.
13
+
14
+ Attributes
15
+ ----------
16
+ code : str or None
17
+ The message code.
18
+ message : str
19
+ The message text with the field values.
20
+ severity : Severity
21
+ The severity of the related event.
22
+ cause : str
23
+ The probable cause.
24
+ remedy : str
25
+ The corrective action.
26
+ fields : dict
27
+ The values of the replacement fields.
28
+ context : dict
29
+ More data about the conditions when the event occurred.
30
+ """
31
+
32
+ #: Message code that the class uses when you do not give a code.
33
+ default_code: ClassVar[Optional[str]] = None
34
+ #: Severity that the class uses when the code has no definition.
35
+ default_severity: ClassVar[Severity] = Severity.ERROR
36
+
37
+ code: Optional[str]
38
+ message: str
39
+ severity: Severity
40
+ cause: str
41
+ remedy: str
42
+ fields: Dict[str, Any]
43
+ context: Dict[str, Any]
44
+
45
+ def _init_coded(
46
+ self,
47
+ message: Optional[str],
48
+ code: Optional[str],
49
+ context: Optional[Mapping[str, Any]],
50
+ cause: Optional[str],
51
+ remedy: Optional[str],
52
+ fields: Mapping[str, Any],
53
+ ) -> str:
54
+ """Set the attributes and return the message text."""
55
+ code = code or self.default_code
56
+ definition = lookup(code)
57
+ self.code = code
58
+ self.fields = dict(fields)
59
+ self.context = dict(context or {})
60
+ if definition is not None:
61
+ text = definition.format(**fields) if message is None else message
62
+ self.severity = definition.severity
63
+ self.cause = cause or definition.cause
64
+ self.remedy = remedy or definition.remedy
65
+ else:
66
+ text = "" if message is None else str(message)
67
+ self.severity = self.default_severity
68
+ self.cause = cause or ""
69
+ self.remedy = remedy or ""
70
+ self.message = text
71
+ return text
72
+
73
+ def __str__(self) -> str:
74
+ if self.code:
75
+ return f"[{self.code}] {self.message}"
76
+ return self.message
77
+
78
+ def with_context(self, **values: Any):
79
+ """Add context data and return the same object.
80
+
81
+ Examples
82
+ --------
83
+ >>> from annunciator import CodedError
84
+ >>> error = CodedError("No data").with_context(sample="S-1")
85
+ >>> error.context
86
+ {'sample': 'S-1'}
87
+ """
88
+ self.context.update(values)
89
+ return self
90
+
91
+ def describe(self) -> str:
92
+ """Return the message, the cause and the remedy as one text."""
93
+ lines = [str(self)]
94
+ if self.cause:
95
+ lines.append(f"Cause: {self.cause}")
96
+ if self.remedy:
97
+ lines.append(f"Remedy: {self.remedy}")
98
+ return "\n".join(lines)
99
+
100
+ def to_dict(self) -> Dict[str, Any]:
101
+ """Return the data of the object as a dictionary."""
102
+ data: Dict[str, Any] = {
103
+ "type": type(self).__name__,
104
+ "code": self.code,
105
+ "severity": self.severity.name,
106
+ "message": self.message,
107
+ "cause": self.cause,
108
+ "remedy": self.remedy,
109
+ "fields": dict(self.fields),
110
+ "context": dict(self.context),
111
+ }
112
+ return {key: value for key, value in data.items() if value not in ("", None, {})}
@@ -0,0 +1,3 @@
1
+ """Version of the :mod:`annunciator` package."""
2
+
3
+ __version__ = "1.1.1"