core: add warnings helper to highlight warnings so they are more visible in the output
This commit is contained in:
parent
cd40fc75c3
commit
fbaa8e0b44
3 changed files with 51 additions and 5 deletions
46
my/core/warnings.py
Normal file
46
my/core/warnings.py
Normal file
|
@ -0,0 +1,46 @@
|
|||
'''
|
||||
A helper to make warnings a bit more visible.
|
||||
TODO ideally would be great to replace with some existing solution, or find a better way,
|
||||
since who looks at the terminal output?
|
||||
E.g. would be nice to propagate the warnings in the UI (it's even a subclass of Exception!)
|
||||
'''
|
||||
|
||||
import sys
|
||||
import warnings
|
||||
|
||||
|
||||
def _colorize(x: str, color=None) -> str:
|
||||
if color is None:
|
||||
return x
|
||||
|
||||
if not sys.stdout.isatty():
|
||||
return x
|
||||
|
||||
# I'm not sure about this approach yet, so don't want to introduce a hard dependency yet
|
||||
try:
|
||||
import termcolor # type: ignore[import]
|
||||
import colorama # type: ignore[import]
|
||||
colorama.init()
|
||||
return termcolor.colored(x, color)
|
||||
except:
|
||||
# todo log something?
|
||||
return x
|
||||
|
||||
|
||||
def _warn(message: str, *args, color=None, **kwargs) -> None:
|
||||
if 'stacklevel' not in kwargs:
|
||||
kwargs['stacklevel'] = 3 # 1 for this function, 1 for medium/high wrapper
|
||||
warnings.warn(_colorize(message, color=color), *args, **kwargs)
|
||||
|
||||
|
||||
def medium(message: str, *args, **kwargs) -> None:
|
||||
kwargs['color'] = 'yellow'
|
||||
_warn(message, *args, **kwargs)
|
||||
|
||||
|
||||
def high(message: str, *args, **kwargs) -> None:
|
||||
'''
|
||||
Meant for deprecations, i.e. things that better get some user attention
|
||||
'''
|
||||
kwargs['color'] = 'red'
|
||||
_warn(message, *args, **kwargs)
|
Loading…
Add table
Add a link
Reference in a new issue