Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to block warnings inside a method

Tags:

python

twitter

So I'm using method_x from a third party library which prints a warning every time I use it. Since I'm coding something that is meant to get user input from the cli I want to block this annoying prints.

import module_x

module_x.method_x() # Has expected behaviour but prints an annoying warning

Is there something I can do to block all the print statements inside a function? Maybe wrapping the method with something or disable stdout temporarily?

Edit: I ended up using a method of the logging module that captures the warnings and redirects them to a log file. Here's the decorator I made:

logging.basicConfig(filename='log/log', level=logging.WARNING)

class redirect_warnings_to_log(object):
    def __init__(self, f):
        self.f = f

    def __call__(self, args):
            logging.captureWarnings(True)
            self.f(args)
            logging.captureWarnings(False)

And here's the decorated method that was printing the warnings:

@redirect_warnings_to_log
def tweet(message):
    twt = api.PostUpdate(message)
like image 792
Phob1a Avatar asked Dec 25 '22 15:12

Phob1a


1 Answers

As the question says -

I'm using method_x from a third party library which prints a warning every time I use it.

If method_x is using Python's warnings module. Then you can use warnings.catch_warnings() along with with statement and warnings.simplefilter() to ignore the warnings , so that warnings are suppressed.

Example -

>>> import warnings
>>> def f():
...     warnings.warn("Some warning!")
...
>>> f()
__main__:2: UserWarning: Some warning!
>>> with warnings.catch_warnings():
...     warnings.simplefilter("ignore")
...     f()
...

Please note this only temporarily suppress warnings, only within the with block, in the f() is used outside the if block, then it does not suppress those warnings.


From documentation -

While within the context manager all warnings will simply be ignored. This allows you to use known-deprecated code without having to see the warning while not suppressing the warning for other code that might not be aware of its use of deprecated code. Note: this can only be guaranteed in a single-threaded application. If two or more threads use the catch_warnings context manager at the same time, the behavior is undefined.

like image 148
Anand S Kumar Avatar answered Jan 08 '23 14:01

Anand S Kumar