warnings — alert developers about code issues without raising exceptions.
1import warnings23# Issue a warning4def deprecated_function():5 warnings.warn(6 "deprecated_function is deprecated, use new_function instead",7 DeprecationWarning,8 stacklevel=29 )10 return new_function()1112# Control warnings13warnings.filterwarnings("ignore", category=DeprecationWarning)14warnings.filterwarnings("error", category=RuntimeWarning)1516# Context manager17with warnings.catch_warnings():18 warnings.simplefilter("ignore")19 deprecated_function() # No warning shown2021# Warning categories22warnings.warn("Default warning", UserWarning) # default23warnings.warn("Deprecated", DeprecationWarning) # deprecated API24warnings.warn("Runtime issue", RuntimeWarning) # runtime
Best practices: