mastering-python / exercises

Example solutions to the exercises from the Mastering Python book
MIT License
11 stars 6 forks source link

Mastering Python - Second Edition: heading: Useless warnings – How to ignore them safely #1 #3

Open vizvasrj opened 2 years ago

vizvasrj commented 2 years ago

I do not understand how that code works ? Where and why and how should I use this.

def _ignore_warning(function):
    @functools.wraps(function)
    def __ignore_warning(*args, **kwargs):
        # Execute the code while catching all warnings
        with warnings.catch_warnings(record=True) as ws:
            # Catch all the warnings of the given type
            warnings.simplefilter('always', warning)
            # Execute the function
            result = function(*args, **kwargs)

        # re-warn all warning beyond the expected count    
        if count is not None:
            for w in ws[count:]:
                warnings.warn(w.message)

        return result

    return __ignore_warning

return _ignore_warning
@ignore_warning(DeprecationWarning, count=1)
def spam():
    warnings.warn('deprecation 1', DeprecationWarning)
    warnings.warn('deprecation 2', DeprecationWarning)

with warnings.catch_warnings(record=True) as ws:
    spam()
    for i, w in enumerate(ws):
        print(w.message)
wolph commented 2 years ago

If you are importing code from an external library that is expected to give a warning, this can help you filter out that specific warning without disabling all warnings.