all Python 3warningsfunction
warnings.showwarning()
displaying warnings
The function the warnings module uses to display each warning that passes the filters; by default it writes to stderr and it can be replaced.
Syntax
warnings.showwarning(message, category, filename, lineno, file=None, line=None)
Replacing warnings.showwarning routes warnings to your own UI or file, but it does not bypass the filters: a silenced warning, or one already shown for that line, never reaches it. Replace it inside catch_warnings(), which restores the original on exit. For logging there is logging.captureWarnings(True), which replaces exactly this function.
Examples
import warnings
def to_stdout(message, category, filename, lineno, file=None, line=None):
print(f'[{category.__name__}] {message}')
with warnings.catch_warnings():
warnings.simplefilter('always')
warnings.showwarning = to_stdout
warnings.warn('кэш устарел')
to_stdout('проверка', UserWarning, '', 0) # → [UserWarning] проверка
See also
Open in the full glossarydocs.python.orgReport an inaccuracy