all Python 3warningsterm
warnings.catch_warnings
filters
A context manager that saves the warning filters and restores them on exit; with record=True it collects warnings into a list instead of printing them.
Syntax
with warnings.catch_warnings(*, record=False, action=None, category=Warning): ...
simplefilter() and filterwarnings() change process-wide settings; inside with catch_warnings(): the changes are rolled back on exit — this is how you silence warnings locally. With record=True warnings are not printed but collected in a list — the way tests check them; but without simplefilter('always') inside the block identical warnings from one line (in a loop, say) are recorded once. In a regular build it mutates global state and is not thread-safe.
Examples
import warnings
def legacy():
warnings.warn('устарело', UserWarning)
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter('always')
legacy()
legacy()
print(len(caught), caught[0].category.__name__) # → 2 UserWarning
# Python 3.11+
import warnings
with warnings.catch_warnings(action='error'):
try:
warnings.warn('устарело', UserWarning)
except UserWarning as e:
print('стало исключением:', e) # → стало исключением: устарело
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy