Skip to content

Commit f27d599

Browse files
committed
misc: Add custom warnings functionality
1 parent 80f1eee commit f27d599

3 files changed

Lines changed: 41 additions & 0 deletions

File tree

devito/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
from devito.builtins import * # noqa
2828
from devito.data.allocators import * # noqa
2929
from devito.logger import error, warning, info, set_log_level # noqa
30+
from devito.warnings import warn # noqa
3031
from devito.mpi import MPI, CustomTopology # noqa
3132
try:
3233
from devito.checkpointing import DevitoCheckpoint, CheckpointOperator # noqa

devito/logger.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,10 @@
2222
CRITICAL = logging.CRITICAL
2323

2424
logging.addLevelName(PERF, "PERF")
25+
# Note: Do not use
26+
# logging.captureWarnings(True)
27+
# here as it will swallow all warnings (not just Devito warnings)
28+
# Instead use the `devito.warnings` module to log warnings
2529

2630
logger_registry = {
2731
'DEBUG': DEBUG,

devito/warnings.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import warnings
2+
3+
from devito.logger import warning as log_warning
4+
5+
6+
class DevitoWarning(Warning):
7+
pass
8+
9+
10+
def warn(message, category=None, stacklevel=2, source=None):
11+
"""
12+
`devito.warn` follows the Python call signature for `warning.warn`:
13+
https://docs.python.org/3/library/warnings.html#warnings.warn
14+
15+
Parameters
16+
----------
17+
message: str or Warning
18+
Message to display
19+
category: None or Warning
20+
Leave as None to get a `DevitoWarning`
21+
stacklevel: int
22+
Set a custom stack level
23+
source: None or object
24+
the destroyed object which emitted a `ResourceWarning`
25+
"""
26+
warning_type = None
27+
if isinstance(message, Warning):
28+
warning_type = message.__class__.__name__
29+
elif category is not None:
30+
warning_type = category.__name__
31+
32+
if warning_type is not None:
33+
message = f'from {warning_type}: {str(message)}'
34+
35+
log_warning(message)
36+
warnings.warn(message, category=DevitoWarning, stacklevel=stacklevel, source=source)

0 commit comments

Comments
 (0)