Control Warnings Separately from Exceptions
Core idea
Warnings communicate conditions that may deserve attention without stopping normal execution by default. A filter can ignore, show or turn a warning into an exception. Use warnings.catch_warnings for a scoped test and choose a relevant category, such as DeprecationWarning for deprecated APIs.
import warningswith warnings.catch_warnings(record=True) as records: warnings.simplefilter('always', UserWarning) warnings.warn('old format', UserWarning) print('continued')print(len(records), records[0].category.__name__)Recording avoids terminal output and preserves category information.
Expected output:
continued1 UserWarningTreat a deprecation as an error in a test
import warningswith warnings.catch_warnings(): warnings.simplefilter('error', DeprecationWarning) try: warnings.warn('use new API', DeprecationWarning) except DeprecationWarning: print('migration needed')The error filter converts the selected warning into a raised exception.
Expected output:
migration neededCommon mistake
Do not globally silence warnings to make tests green. Filter a specific known category and fix the root issue. In Python 3.13 warning filter state is process-wide, so scoped changes are not generally thread-safe.
Practice
Capture two UserWarnings at the same location using always and default filters in separate runs and compare counts.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Warnings
Check your understanding of warnings.
What is printed?
import warningswith warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") warnings.warn("notice")print(len(w))What is printed?
import warningswith warnings.catch_warnings(): warnings.simplefilter("error",UserWarning) try: warnings.warn("x") except UserWarning: print("caught")Which filter makes a matching warning raise?
What is the best response to a new dependency deprecation?