46 lines
1.3 KiB
Python
46 lines
1.3 KiB
Python
'''
|
|
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)
|