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.
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,
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 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.
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.
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.
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.
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.
Other than these warnings, there are a few others like
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
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.
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.
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.
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)
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(action, message, category, module, lineno)
In the above code, the action we used is
ignore which never prints a warning message.
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.
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.
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.
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.
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.