Back to results for “Debugging”
Python › Debugging & Profiling

How do you use Python's built-in 'warnings' module to surface deprecated or risky code paths during debugging?

Intermediate

Answer

warnings.warn(message, category) emits a runtime warning without stopping execution, and running Python with -W error (or filterwarnings('error')) turns warnings into exceptions during testing, helping catch deprecated API usage before it becomes a hard failure in a future version.
import warnings

def old_function():
    warnings.warn("old_function is deprecated, use new_function instead", DeprecationWarning)
    return new_function()

# During testing: python -W error::DeprecationWarning script.py  -- turns the warning into an exception
Real-world example Flagging a deprecated internal API during a migration so callers get an early, non-fatal signal to update before it's removed.

Common follow-ups: How do you configure a custom warnings filter to show a warning only once, instead of every time it's triggered?