Enabling and disabling custom wanings

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Jul 13 09:09:44 EDT 2018


I have a warning that my code generates using the warning module:

https://docs.python.org/3/library/warnings.html


def spam(n):
    if n < 10:
        warnings.warn("not enough spam!")
    return "spam" * n


By default, I want this warning to be disabled, but I want the user to be 
able to enable or disable that warning at runtime. This is the code I use:


def enable():
    warnings.filterwarnings("always",
              category=UserWarning, module=__name__)

def disable():
    warnings.filterwarnings("ignore",
              category=UserWarning, module=__name__)


Am I doing it right?



-- 
Steven D'Aprano
"Ever since I learned about confirmation bias, I've been seeing
it everywhere." -- Jon Ronson



More information about the Python-list mailing list