Как убрать вывод ошибок python

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

There are times when the compiler informs the user of a condition in the program while the code is being executed. When it is necessary to advise the user of a program condition that (usually) doesn’t require raising an exception or terminating the program, warning messages are typically sent. Mostly, these warnings are descriptive of some underlying fault at work. But sometimes, they may not be required. This article will make you understand how to disable Python warnings in a very simple manner.

What are Python warnings?

Warnings are provided to warn the developer of situations that aren’t necessarily exceptions. Usually, a warning occurs when certain programming elements are obsolete, such as keyword, function or class, etc. A warning in a program is distinct from an error. Python program terminates immediately if an error occurs. Conversely, a warning is not critical. It shows some messages, but the program runs.

Example:

The following is a warning that occurs when the path environment variable does not contain the path to the scripts folder of the Python distribution.

How to disable Python warnings?

The pip module was reinstalled, and a warning appeared during the process.

Again, the task at hand (reinstalling pip) was successfully completed, but the compiler warned about an irregularity detected in the paths. Regardless of whether the issue is resolved or not, it did not have a direct impact on the task. But this may not always be true.

How to Disable Python Warnings?

There are two ways in which warnings can be ignored:

  • Disabling warnings from the code
  • Disabling warnings with Command

Disabling warnings from the code

To disable warnings from the code, the use of the warnings module would be made, and all the warnings would be filtered to be ignored. Hence, no warning would appear in the output. First, we will generate code that won’t need to turn off warnings, and then we will generate code that will. The warning is not disabled in the following code:

Python3

import warnings

print('Hello')

warnings.warn('Error: A warning just appeared')

print('Geeks !')

Output:

How to disable Python warnings?

In the above code, a self-generated warning message was displayed. Since, by default, the program has warnings enabled, the message was displayed, and the warning appeared. Now, the warnings are disabled, then an attempt to display the warning has been made:

Python3

import warnings

print('Hello')

warnings.filterwarnings('ignore')

warnings.warn('Error: A warning just appeared')

print('Geeks !')

Output:

The output of the code omitted the warning due to the second statement, which calls the filterwarnings function and passes ignore as an argument. This filters all the warnings occurring during the code to be ignored. Due to this, the warning in the next statement didn’t appear. 

How to disable Python warnings?

Disabling Python Warnings with Command

In case the contents of the code can’t be modified to integrate the previous method into it, warnings can be disabled from the outside. This is done by passing the ignore argument to the -W switch of the Python compiler. 

-W arg : warning control; arg is action:message:category:module:lineno
        also PYTHONWARNINGS=arg

Hence, by integrating the -W “ignore” string in the command to execute the first code, the warnings in the code could be disabled. The code that is to be run from the command line would be:

py -W "ignore" test.py

How to disable Python warnings?

The Python interpreter is instructed to disable the warnings before the execution of the test.py file (used in the first example). Similarly, using the following syntax:

py -W "ignore" "_filename_"

Warnings could be ignored during the execution of files containing Python code.

Last Updated :
05 Feb, 2023

Like Article

Save Article

If you are a python programmer or have worked with coding on Python, you definitely would have faced warnings and errors when compiling or running the code. Therefore in this article, we are going to discuss How to suppress warnings in Python.

In some cases, when you want to suppress or ignore warnings in Python, you need to use some specific filter function of the warnings module. We will discuss the usage of those functions in this article. Thus, you can learn to ignore or suppress warnings when needed.

Suppress Warnings In Python - All You Need To Know

The pip module was reinstalled, and a warning appeared during the process.

Again, the task at hand (reinstalling pip) was successfully completed, but the compiler warned about an irregularity detected in the paths. Regardless of whether the issue is resolved or not, it did not have a direct impact on the task. But this may not always be true.

How to Disable Python Warnings?

There are two ways in which warnings can be ignored:

  • Disabling warnings from the code
  • Disabling warnings with Command

Disabling warnings from the code

To disable warnings from the code, the use of the warnings module would be made, and all the warnings would be filtered to be ignored. Hence, no warning would appear in the output. First, we will generate code that won’t need to turn off warnings, and then we will generate code that will. The warning is not disabled in the following code:

Python3

import warnings

print('Hello')

warnings.warn('Error: A warning just appeared')

print('Geeks !')

Output:

How to disable Python warnings?

In the above code, a self-generated warning message was displayed. Since, by default, the program has warnings enabled, the message was displayed, and the warning appeared. Now, the warnings are disabled, then an attempt to display the warning has been made:

Python3

import warnings

print('Hello')

warnings.filterwarnings('ignore')

warnings.warn('Error: A warning just appeared')

print('Geeks !')

Output:

The output of the code omitted the warning due to the second statement, which calls the filterwarnings function and passes ignore as an argument. This filters all the warnings occurring during the code to be ignored. Due to this, the warning in the next statement didn’t appear. 

How to disable Python warnings?

Disabling Python Warnings with Command

In case the contents of the code can’t be modified to integrate the previous method into it, warnings can be disabled from the outside. This is done by passing the ignore argument to the -W switch of the Python compiler. 

-W arg : warning control; arg is action:message:category:module:lineno
        also PYTHONWARNINGS=arg

Hence, by integrating the -W “ignore” string in the command to execute the first code, the warnings in the code could be disabled. The code that is to be run from the command line would be:

py -W "ignore" test.py

How to disable Python warnings?

The Python interpreter is instructed to disable the warnings before the execution of the test.py file (used in the first example). Similarly, using the following syntax:

py -W "ignore" "_filename_"

Warnings could be ignored during the execution of files containing Python code.

Last Updated :
05 Feb, 2023

Like Article

Save Article

If you are a python programmer or have worked with coding on Python, you definitely would have faced warnings and errors when compiling or running the code. Therefore in this article, we are going to discuss How to suppress warnings in Python.

In some cases, when you want to suppress or ignore warnings in Python, you need to use some specific filter function of the warnings module. We will discuss the usage of those functions in this article. Thus, you can learn to ignore or suppress warnings when needed.

Suppress Warnings In Python - All You Need To Know

Warnings And Its Types

A warning in Python is a message that programmer issues when it is necessary to alert a user of some condition in their code. Although this condition normally doesn’t lead to raising an exception and terminating the program. Let’s understand the types of warnings.

The table given above shows different warning classes and their description.

Class Description
BytesWarning Base category for warnings related to bytes and bytearray.
DeprecationWarning Base category for warnings about deprecated features when those warnings are intended for other Python developers (ignored by default, unless triggered by code in main).
FutureWarning Base category for warnings about deprecated features when those warnings are intended for end users of applications written in Python.
ImportWarning Base category for warnings triggered during the process of importing a module (ignored by default).
PendingDeprecationWarning Base category for warnings about features that will be deprecated in the future (ignored by default).
ResourceWarning Base category for warnings related to resource usage (ignored by default).
RuntimeWarning Base category for warnings about dubious runtime features.
SyntaxWarning Base category for warnings about dubious syntactic features.
UnicodeWarning Base category for warnings related to Unicode.
UserWarning The default category for warn().
Warning This is the base class of all warning category classes. It is a subclass of Exception.
Table 1.1

Just like everything in Python is an object, similar warnings are also objects in Python. You can program them too. You have to use the ‘warnings’ package to ignore warnings. Firstly we will see how you can ignore all warnings in python step by step:

  1. Import ‘warnings’ module
  2. Use the ‘filterwarnings()’ function to ignore all warnings by setting ‘ignore’ as a parameter.
import warnings
warnings.filterwarnings('ignore') # setting ignore as a parameter

Suppress Specific Warnings In Python

Further, let’s see how to suppress specific warnings in Python using the warnings package. For stopping particular signs, we will need to add another parameter in the ‘filterwarnings()’ function, i.e., category.

  1. import warnings
  2. Use the ‘filterwarnings()’ function to ignore all warnings by setting ‘ignore’ as a parameter. In addition to that, add a parameter ‘category’ and specify the type of warning.
import warnings
warnings.filterwarnings(action='ignore', category=FutureWarning) # setting ignore as a parameter and further adding category

Similarly, you can add any category you desire and suppress those warnings.

Suppressing Pandas warnings

You can even suppress pandas warnings in order to do that. You have to write a code to suppress warnings before importing pandas.

import warnings
warnings.simplefilter(action='ignore', category=FutureWarning) # setting ignore as a parameter and further adding category

import pandas

Suppressing Warnings In Tensorflow

Further, you can even ignore tensorflow warnings if you want. The way to ignore warnings in tensorflow is a bit different. Let’s understand step by step:

  • For TF 2.x, you can use the following code
tf.logging.set_verbosity(tf.logging.ERROR)
  • For TF 1.x, you can use the following code
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)

The codes mentioned above are used to remove logging information. Therefore any messages will not be printed. Further, if you want to remove deprecated warnings or future warnings in TF 1. x, you can use:

from tensorflow.python.util import deprecation
deprecation._PRINT_DEPRECATION_WARNINGS = False

To suppress futurewarnings along with current deprecated warnings, use:

import warnings
warnings.filterwarnings('ignore', category=DeprecationWarning)
warnings.filterwarnings('ignore', category=FutureWarning)

Suppress Warnings in Python IDE (Pycharm)

When you use an IDE like Pycharm, you can disable inspections, so no warnings are raised. Moreover, you can also suppress a warning for a particular line of code.

  • Disable warnings for a particular line of code.
from application import routes  # noqa

By commenting ‘noqa,’ you can suppress warnings for that single line of code. In addition to that, if you want to suppress all warnings, you can follow these given steps:

  1. Go to Settings dialog (Ctrl+Alt+S) and select Editor/Inspections.
  2. And then go to the inspection you want to disable, further uncheck the checkbox next to it.
  3. Apply the changes and close the dialog box.

Suppress Pylint Warnings

To disable pylint warnings, you can also use the symbolic identities of warnings rather than memorize all the code numbers, for example:

# pylint: disable=locally-disabled, multiple-statements, fixme, line-too-long

You can use this comment to disable any warnings for that line, and it will apply to the code that is coming after it. Similarly, it can be used after an end of a line for which it is meant.

Disable Warnings In Jupyter Notebook

You can suppress all warnings in the jupyter notebook by using the warnings module and using functions like ‘simplefilter()’ and ‘filterwarnings()’.

import warnings
warnings.filterwarnings('ignore')
warnings.simplefilter('ignore')

Further, to suppress warnings for a particular line of codes, you can use :

import warnings

def warning_function():
    warnings.warn("deprecated", DeprecationWarning)

with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    warning_function() #now warnings will be suppressed 

Disable Warning While Ansible Execution

You can disable all the warnings when using ansible by making the deprecation_warnings = ‘false’ in defaults section of your effective configuration file i.e.(/etc/ansible/ansible.cfg, ~/.ansible.cfg).

Suppress Matplotlib Warnings

To suppress the matplotlib library, first import all required modules in addition to that import warnings module. Further use the’ filterwarnings()’ function to disable the warnings.

import numpy as np
from matplotlib import pyplot as plt
import warnings
warnings.filterwarnings("ignore")

Then finish writing your remaining code, you will see no warnings pop up, and the code will be executed.

Disable SSL Warnings Python Requests

Further, let’s see how you can disable security certificate checks for requests in Python.

When we use the requests module, we pass ‘verify = False’ along with the URL, which disables the security checks.

import requests
  
# sending a get http request to specified link URL
response = requests.request(
    "GET", "https://www.yoururlhere.com", verify=False)

Bypassing the ‘verify=False,’ you can make the program execute without errors.

FAQs on Suppress Warnings Python

How do I turn off warnings in Python?

You can use the ‘filterwarnings()’ function from the warnings module to ignore warnings in Python.

How do I ignore Numpy warnings?

You can use the syntax ‘np.seterr(all=”ignore”)’ to ignore all warnings.

How to Re-enable warnings in Python

You can use the ‘filterwarnings()’ function from the warnings module and set ‘default’ as a parameter to re-enable warnings.

Conclusion

In this article, we have seen how we can suppress warnings when needed, although warnings are essential as they can signify a problem you might leave unseen. Therefore it is advised to code with warnings enabled. Only disable them when it is of utmost importance to ignore them.

To learn something new and exciting, check out this post.

Reference

Reference for “Table 1.1” is official python documentation (python 3.10.6 documentation) https://docs.python.org/3/library/warnings.html

Trending Python Articles

  • [Solved] typeerror: unsupported format string passed to list.__format__

    [Solved] typeerror: unsupported format string passed to list.__format__

    May 31, 2023

  • Solving ‘Remote End Closed Connection’ in Python!

    Solving ‘Remote End Closed Connection’ in Python!

    by Namrata GulatiMay 31, 2023

  • [Fixed] io.unsupportedoperation: not Writable in Python

    [Fixed] io.unsupportedoperation: not Writable in Python

    by Namrata GulatiMay 31, 2023

  • [Fixing] Invalid ISOformat Strings in Python!

    [Fixing] Invalid ISOformat Strings in Python!

    by Namrata GulatiMay 31, 2023

In Python programming language or in general programming, we often come across with different kinds of warnings and errors. Some are expected and some are unexpected. Developers come across the situations where he/she needs to remove the expected warning. So, In this Python tutorial article we will learn about some methods using which we can stop/disable Python warnings.

Table Of Contents

  • Warnings vs Error
  • warn() function
  • Method 1 : Using simplefilter()
  • Method 2 : Using filterWarning()
  • SUMMARY

Warnings vs Error

When an error occurs in Python Programming language, the program immediately stops but not the same in the case of warnings, Python interpreter warns about certain exception and continues the program.

Advertisements

  • Categories of Warnings :
  • Warning
  • UserWarning
  • DeprecationWarning
  • SyntaxWarning
  • RuntimeWarning
  • FutureWarning
  • PendingDeprecationWarning
  • ImportWarning
  • UnicodeWarning
  • BytesWarning
  • ResourceWarning

warn() function

In Python Programming language we have a warn() function of warning module, which is similar to the PyErr_WarnEx() which is used in C++. This function is used to show warning message or it can also be used to ignore certain warnings which developer is expecting in the code.

Here is an example code with Warnings

Frequently Asked:

  • Pandas : How to Merge Dataframes using Dataframe.merge() in Python – Part 1
  • Replace NaN values with next values in Pandas
  • Get every Nth element from a list of tuples in python
  • Python Pandas : How to create DataFrame from dictionary ?

CODE :

#importing the warning module
import warnings

# Creating an example warning message using warn() function.
warnings.warn('DemoWarning : This is an example warning message.')

print('abcd')

OUTPUT :

DemoWarning : This is an example warning message.
 warnings.warn('DemoWarning : This is an example warning message.')
abcd

In the above example code and output you can see, a warning message has been created using the warn() function of warning module. Now Let’s learn about warnings filter then we will learn about some methods using which we can stop/disable Python warnings.

Warnings Filter

Latest Python — Video Tutorial

In the warnings module we have a warning filter which contorls whether the warnings will be ignored, displayed or it will be displayed as an error(exceptions). In the warnings filter we have an ordered list of filter specifications, warnings are matched against there filter specification.

Method 1 : Using simplefilter()

First method we can use to stop/disable Python warnings is by using simplefilter() function of warnings module. This module comes pre-installed with python programming language, this method filter outs all the warnings. When actions = ‘ignore’ is passed in the parameter, then this filters all the warning.

SYNTAX : warnings.simplefilter(action, category=warnings, lineno=0, append=False)

This method receives four parameters which are as follows:

  • actions
Actions Disposition
“default” prints the warning message with line number.
“ignore” This will not print any warning.
“always” Always prints the matching warning.
“module” Prints the first warning for each module.
“once” Prints only the first matching warning.
“error” This turns the warnings message into an error.
  • category : a class which the warning category must be a subclass.
  • lineno : Integer, warning of line number to be filtered. This should, must match.
  • append : Boolean, default is false. Default value to inseert entry is front. If append is true, then the entry will be inserted at the end.

See an example code below

CODE :

#importing warning module
import warnings

# Creating an example warning message using warn() function.
warnings.warn('DemoWarning : This is an example warning message.')

# using simplefilter() to stop/disable warnings.
warnings.simplefilter(action='ignore')

print('abcd')

OUTPUT :

abcd

In the above code and output you can see warning message has been filtered by using the simplefilter() method of warnings module. You can see action=’ignore’ has been passed which will ignore/filter all the warning message.

Method 2 : Using filterWarning()

Another method we will be using is the filterwarnings() method of warnings module. This method is similar to the method above which is the simplefilter() method but it has some finer filtration methods. In this method you can filter out all the warning from a specific given module.

This method receives six parameters which are as follows:

Actions Disposition
“default” prints the warning message with line number.
“ignore” This will not print any warning.
“always” Always prints the matching warning.
“module” Prints the first warning for each module.
“once” Prints only the first matching warning.
“error” This turns the warnings message into an error.
  • message : String, a regular expression at the beginning of the message which must macth.
  • category : a class which the warning category must be a subclass.
  • module : String, used to set a regular expression to filter warning message of any specific module.
  • lineno : Integer, warning of line number to be filtered. This should, must match.
  • append : Boolean, default is false. Default value to inseert entry is front. If append is true, then the entry will be inserted at the end.

SYNTAX : warnings.filterwarning(action,message='',category=Warning,module='', lineno=0, append=False)

Now lets see an example code.

CODE :

#importing warning module
import warnings

# Creating an example warning message using warn() function.
warnings.warn('DemoWarning : This is an example warning message.')

# using filterwarnings() to stop/disable warnings.
warnings.filterwarnings('ignore')

print('abcd')

OUTPUT :

abcd

In the above code and output, you can see we have used warnings.filterwarning() to stop/disable Python warnings which is being generated by warnings.warn() function.

SUMMARY

In this Python tutorial article of How to stop/disable Python warnings you can see we have used two methods of warnings module to filterout all the warnings that are being generated by warnings.warn() function. Both of these methods can be used to filter out all warnings that are being generated by the Python Interpreter. Also we have learned about types of warnings and Warnings Filter.

You can always use both the methods according to your use. Like if you are working with various modules and getting some warning in any specific module, then you can use the filterwarnings() method and pass the module name as an argument in this function to filter out all the warnings generated from that module.

Make sure to read/write to code to have a better understanding of this problem.

Thanks

A warning is typically used to alert someone of a situation that they might encounter, which doesn’t need to be true all the time.

In the same way, warnings in Python are used to alert the programmers of a situation that is not an exception. They are used to alert the programmer of a problem that doesn’t interrupt the code flow but might result in unexpected code behavior.

Many variants of the warnings a user might encounter while coding exists. While they are helpful in letting us know what might happen in some instances, they might be irritating if they occur frequently.

In this tutorial, we will learn about warnings, their variants, and how we can disable such warnings.

Before we discuss this further, visit this article to learn about the Python modules.

What Is a Warning?

As discussed above, warnings are used to alert programmers about a situation that does not terminate the program or raise any exception but sometimes can lead to unexpected behavior of the code. One popular case is where a warning message is printed when the user is trying to use a module or a package that is no longer used or outdated. A warning is different from an exception. While a code cannot be executed further in case of an exception, in a warning’s case, the code runs as usual.

There is a dedicated module in Python called warnings which can be referred to learn about the warnings and how they generally function.

Difference Between Warning and Error

While both warnings and errors are used to let the programmers know there is an issue with their code, there is a significant difference between them.

Errors are critical. An error occurs when there is something wrong with the code that has to be corrected for the code to run properly. When an error occurs, the IDE raises an exception, which should be solved for the code to resume execution.

Warnings are not critical. They are used to alert the programmer about an unexpected behavior that might occur. They do not interfere with the code’s execution.

Related: Visit this article to know more about exceptions in Python.

Let us see an example of an error and warning.

The code that runs into an error is given below.

As you can see, the above code generates a syntax error because the quotes(‘ ‘) are not closed properly.

Error

Error

Now let us see a warning

#warning
import warnings
print('Hello World')
warnings.warn("This is a warning")
print('HelloWorld2') 

We cannot implement warnings without importing the warnings module. We are trying to print a simple message in the third line.

Then, we are using the warnings module to generate a warning message.

In the next line, we are printing another message using the print function.

This is done to check if the flow of the code execution is interrupted when there is a warning,

Warning

Warning

Unlike errors, the code after warnings is still executed.

Categories of Warnings

There are around ten types of warnings according to the Python documentation. Let us cover all of them one by one.

UserWarning

The UserWarning is the default category of the warn() method. This warning is used to notify the user about an issue that might occur later in the code.

One example of using the warn() method to generate a UserWarning is given below.

import warnings
print('This is a message')
warnings.warn("This is a warning")
print('This is another message')

The output is shown below.

UserWarning

UserWarning

DepreciationWarning

The depreciation warning is used to warn the users of a library or a package that a particular feature is going to be removed or will be updated in the newer versions.

The depreciation warnings are used by the developers of the library to alert the users to update their existing library version to be able to use the new features.

Let us see an example of such a warning.

import warnings
import numpy as np
a = np.bool_([0,1,0,1])
print(a)

In the above code, we are trying to print the truth values(True and False) associated with 0 and 1.

We are using the np.bool_constructor of the numpy library to print the truth values.

This code is supposed to display a warning message because the above-used constructor is no longer in practice or is depreciated.

Depreciation Warning

Depreciation Warning

Here is the full warning message.

[False True False True]
/usr/local/lib/python3.9/dist-packages/ipykernel/ipkernel.py:283: DeprecationWarning: `should_run_async` will not call `transform_cell` automatically in the future. Please pass the result to `transformed_cell` argument and any exception that happen during thetransform in preprocessing_exc_tuple in IPython 7.17 and above.
and should_run_async(code)

The reason why we are seeing this warning message is that Numpy has recently depreciated the np.bool_ constructor in the newer versions starting from 1.20.0. We can check the release notes of a version to know the depreciated functions or constructors.

SyntaxWarning

As the name suggests, this warning will be displayed when the user is trying to execute a code that is syntactically wrong.

import warnings
r = 3 is 2
print(r)

Observe the code. The code just doesn’t make any sense. If we want to compare the value of two numbers, we are supposed to be using the == operator. But in the above code, we are trying to check if the two numbers are equal using the is operator which is used to compare the objects based on their identity.

Syntax Warning

Syntax Warning

Other than these warnings, there are a few others like RuntimeWarning, FutureWarning, ImportWarning and so on which might depend on the version of Python you are using and also the IDE in which you are executing the code.

How to Create Custom Warnings?

We can also display our own warnings in a code that might have an issue. We can print any custom warnings of our choice based on the code with the help of the methods of the warnings module. There are a few ways to do this.

Using the Warnings Module

In this example, we are going to import the warnings module and use its methods to display a custom warning message.

import warnings
def func(z):
    if z < 0:
        warnings.warn("Oh! It is a negative number!", UserWarning)
    return z + 11
func(-4)

This code generates a warning if the argument we are trying to pass to the func function is a negative number. Since this is intended for the user, this warning falls into the category of UserWarning.

So we have a function called func, which takes a parameter called z. This function is created using the def keyword.

Inside this function, there is an if statement checking if the input is less than zero. If it is so, this code displays a warning message – “Oh! It is a negative number!”.

return z+11 is used to compute the sum of the argument we passed to the function and the number 11.

We are also trying to call the func with some argument. The argument we passed is -4 which is negative so the code should display a warning message.

Custom Warning

Custom Warning

Creating a Custom Warning Class

In this example, we will define a custom class for the warning and call it in the warning message.

import warnings
class warn1(Warning):
    pass
def  func(y):
    if y < 0:
        warnings.warn("Oops! A negative number!", warn1, stacklevel=2)
    return y + 1
func(-10)

In the above code, we have imported the warnings module in the first line. Next, we defined a custom class called warn1 which takes Warning as an argument. The keyword pass is used to prevent the class definition from being empty as there are no statements in the class.

We have used the same function from the previous example.

In the sixth line, we are passing the class name as an argument to the warn method with stacklevel=2 which means, only the warning is displayed without the source of the warning.

Custom Class For The Warning

Custom Class For The Warning

The default value of stacklevel is 1, which means the source of the warning is also displayed in the output.

Here is a comparison of the stacklevel being 1 and 2.

Stacklevel- 1 Vs 2

Stack level- 1 Vs 2

How to Disable Warnings?

Agreed that warnings are useful to alert the user about a potential issue and also might come in handy for the developers to introduce changes or updations of the existing libraries or packages, you cannot deny that it sure becomes annoying if you repeatedly get warnings and the worst case, if you get the same warning again and again.

There are a few approaches to shut the warnings that might occur in your code.

Using the filterwarnings()

We can use the filterwarnings method of the warnings module to get rid of any potential warnings. Let us see an example of how we can shut down the depreciation warnings that occurred in the previous examples.

import warnings
import numpy as np
warnings.filterwarnings("ignore")
a = np.bool_([0,1,0,1])
print(a)

The np.bool_ constructor used in the above code is supposed to raise a warning as it is depreciated in the newer versions of the numpy library. So to avoid this warning, we are using the filterwarnings from the warnings module.

The syntax of the filterwarnings is shown below.

filterwarnings(actionmessagecategorymodulelineno)

In the above code, the action we used is ignore which never prints a warning message.

Disable Depreciation Warning

Disable Depreciation Warning

Using the filterwarnings() And Specifying the Category

In the previous example, we have seen the syntax of filterwarnings(). In this example, we are going to specify the category of the warnings we don’t want to be displayed.

import warnings
warnings.filterwarnings('ignore',category=SyntaxWarning)
x = 41
if x is 41:
    print("The number is 41")

This code is bound to display an error message because the is operator is used to compare the identity and not the value. But here, we are using it to compare the value. So it generates a Syntax Warning.

We are specifying the category as SyntaxWarning so that all the syntax-based warnings are ignored.

Disable Syntax Warning

Disable Syntax Warning

Using shut up

Shutup is a third-party open source module used to silence the warnings. Here is an image showing the usage of this module.

Shut Up

Shut Up

Let us see if we can silence the warnings by shut up.

import shutup; shutup.please()
import warnings
class warn1(Warning):
    pass
def  func(y):
    if y < 0:
        warnings.warn("Oops! A negative number!", warn1, stacklevel=2)
    return y + 1
func(-10)

This code has the warning message included. So if we did not use the shut up module, the code definitely generates a warning message.

Disable Warning Using Shutup

Disable Warning Using Shutup

Conclusion

Warnings are messages used to alert the user about any potential issue or any updates in the libraries or packages they are using. Unlike errors, they do not terminate the code.

There can be many variants of the warnings a user might encounter while coding. While they are useful to let us know what might happen in certain cases, they might be irritating if they occur frequently.

A warning is different from an error. While a code with an error does not execute until the error is solved, a code with a potential warning does not terminate if a warning occurs. We have seen examples of both warnings and errors and observed how they function.

Based on the situation, we can categorize the warnings into many types. They are UserWarning, SyntaxWarnings, DepreciationWarning, FutureWarnings, and so on.

We have seen how to generate a custom warning. We tried to generate a custom warning using the warn function of the warnings module. In the next example, we have seen how to use a custom class to generate a warning message.

References

Visit the Python documentation to know more about the warnings module.

Check out the release notes of the Numpy library for depreciated methods in version 1.20.0.

Check out the documentation of Shutup.

Понравилась статья? Поделить с друзьями:
  • Как убрать vac ошибку как убрать vac ошибку
  • Как убрать всплывающие ошибки в wow
  • Как убрать 404 ошибку wordpress
  • Как убрать всплывающие ошибки в windows
  • Как убирать ошибки с магнитолы пионер