I have a use case to override default warning handling behavior for a specific class of warning. warnings.showwarning will override the handling for all warnings generated and not thread safe as well. warnings.simplefilter allows to override behavior for specific class of warnings but override options are limited. Maybe warnings.showwarning can also have an optional parameter for warning catergory(any object derived from warning object).
1 Like
I think you can do this with the current module:
import warnings
# Define a custom warning subcategory
class DemoWarning(Warning):
"""Custom demo warning."""
pass
# Save the original showwarning function
original_showwarning = warnings.showwarning
def custom_showwarning(message, category, filename, lineno, file=None, line=None):
# Check if the warning is a DemoWarning (or subclass)
if issubclass(category, DemoWarning):
log_file_path = '/tmp/demo_warning.log'
with open(log_file_path, 'a') as log_file:
log_file.write(f"{filename}:{lineno}: {category.__name__}: {message}\n")
else:
# For all other warnings, call the original showwarning function
original_showwarning(message, category, filename, lineno, file, line)
# Override the default warnings.showwarning with our custom function
warnings.showwarning = custom_showwarning
# Trigger a demo warning that should be logged to /tmp/demo_warning.log
warnings.warn("This is a demo warning", DemoWarning)
# Trigger another warning from a different category that will use the original showwarning behavior
warnings.warn("This is a regular warning", UserWarning)
Yes this would work as long as there isn’t another place in the application where we end up overriding the showwarning function in a different way(maybe to handle a different Warning class). User would then have to ensure thread safety for this. Same approach could be used even for all the functionalities warnings.simplefilter is offering for that matter. I am just wondering a cleaner and more convenient approach would be for the module to handle this natively.