Python (default)

Regular output

1 + 1
2

Errors

1 + a
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[2], line 1
----> 1 1 + a

NameError: name 'a' is not defined

Warnings

Python’s warning system is a lot more complicated than R’s. The warnings module provides support for many different kinds of focused warnings, like UserWarning, SyntaxWarning, and UnicodeWarning, among others.

To make nicer warnings here, we use warnings.formatwarning to get rid of file names and line numbers:

import warnings

def simple_warning(message, category, filename, lineno, file=None, line=None):
    return f"{category.__name__}: {message}\n"

warnings.formatwarning = simple_warning
warnings.warn("Here's a warning")
UserWarning: Here's a warning

It’s also common to not use warnings and to instead write text directly to stderr.

import sys
print("Warning: Be careful!", file=sys.stderr)
Warning: Be careful!