Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
vizvasrj opened this issue Oct 10, 2022 · 1 comment

Comments

@vizvasrj
Copy link

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
Copy link
Member

wolph commented Oct 17, 2022

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants