Skip to content

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

@vizvasrj

Description

@vizvasrj

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)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions