How to disable Python warnings?

Posted on

Solving problem is about exposing yourself to as many situations as possible like How to disable Python warnings? and practice these strategies over and over. With time, it becomes second nature and a natural way you approach any problems in general. Big or small, always start with a plan, use other strategies mentioned here till you are confident and ready to code the solution.
In this post, my aim is to share an overview the topic about How to disable Python warnings?, which can be followed any time. Take easy to follow this discuss.

How to disable Python warnings?

I am working with code that throws a lot of (for me at the moment) useless warnings using the warnings library. Reading (/scanning) the documentation I only found a way to disable warnings for single functions. But I don’t want to change so much of the code.

Is there a flag like python -no-warning foo.py?

What would you recommend?

Answer #1:

There’s the -W option.

python -W ignore foo.py
Answered By: Pavel Anossov

Answer #2:

Look at the Temporarily Suppressing Warnings section of the Python docs:

If you are using code that you know will raise a warning, such as a deprecated function, but do not want to see the warning, then it is possible to suppress the warning using the catch_warnings context manager:

import warnings
def fxn():
    warnings.warn("deprecated", DeprecationWarning)
with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    fxn()

I don’t condone it, but you could just suppress all warnings with this:

import warnings
warnings.filterwarnings("ignore")

Ex:

>>> import warnings
>>> def f():
...     print('before')
...     warnings.warn('you are warned!')
...     print('after')
...
>>> f()
before
<stdin>:3: UserWarning: you are warned!
after
>>> warnings.filterwarnings("ignore")
>>> f()
before
after
Answered By: Mike

Answer #3:

You can also define an environment variable (new feature in 2010 – i.e. python 2.7)

export PYTHONWARNINGS="ignore"

Test like this: Default

$ export PYTHONWARNINGS="default"
$ python
>>> import warnings
>>> warnings.warn('my warning')
__main__:1: UserWarning: my warning
>>>

Ignore warnings

$ export PYTHONWARNINGS="ignore"
$ python
>>> import warnings
>>> warnings.warn('my warning')
>>> 

For deprecation warnings have a look at how-to-ignore-deprecation-warnings-in-python

Copied here…

From documentation of the warnings module:

 #!/usr/bin/env python -W ignore::DeprecationWarning

If you’re on Windows: pass -W ignore::DeprecationWarning as an argument to Python. Better though to resolve the issue, by casting to int.

(Note that in Python 3.2, deprecation warnings are ignored by default.)

Or:

import warnings
with warnings.catch_warnings():
    warnings.filterwarnings("ignore", category=DeprecationWarning)
    import md5, sha
yourcode()

Now you still get all the other DeprecationWarnings, but not the ones caused by:

import md5, sha
Answered By: Holger Bille

Answer #4:

This is an old question but there is some newer guidance in PEP 565 that to turn off all warnings if you’re writing a python application you should use:

import sys
import warnings
if not sys.warnoptions:
    warnings.simplefilter("ignore")

The reason this is recommended is that it turns off all warnings by default but crucially allows them to be switched back on via python -W on the command line or PYTHONWARNINGS.

Answered By: Chris_Rands

Answer #5:

If you don’t want something complicated, then:

import warnings
warnings.filterwarnings("ignore", category=FutureWarning)
Answered By: Abhishek Jain

Answer #6:

If you know what are the useless warnings you usually encounter, you can filter them by message.

import warnings
#ignore by message
warnings.filterwarnings("ignore", message="divide by zero encountered in divide")
#part of the message is also okay
warnings.filterwarnings("ignore", message="divide by zero encountered")
warnings.filterwarnings("ignore", message="invalid value encountered")
Answered By: user3226167

Answer #7:

I realise this is only applicable to a niche of the situations, but within a numpy context I really like using np.errstate:

np.sqrt(-1)
__main__:1: RuntimeWarning: invalid value encountered in sqrt
nan

However, using np.errstate:

with np.errstate(invalid='ignore'):
    np.sqrt(-1)
nan

The best part being you can apply this to very specific lines of code only.

Answered By: jorijnsmit

Answer #8:


More pythonic way to ignore WARNINGS


Since ‘warning.filterwarnings()‘ is not suppressing all the warnings, i will suggest you to use the following method:

import logging
for name in logging.Logger.manager.loggerDict.keys():
    logging.getLogger(name).setLevel(logging.CRITICAL)
#rest of the code starts here...

OR,

If you want to suppress only a specific set of warnings, then you can filter like this:

import logging
for name in logging.Logger.manager.loggerDict.keys():
    if ('boto' in name) or ('urllib3' in name) or ('s3transfer' in name) or ('boto3' in name) or ('botocore' in name) or ('nose' in name):
            logging.getLogger(name).setLevel(logging.CRITICAL)
#rest of the code starts here...
Answered By: Safvan CK

Leave a Reply

Your email address will not be published. Required fields are marked *