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')
  
# Displaying a warning message
warnings.warn('Error: A warning just appeared')
  
print('Geeks !')


Output:

 

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')
  
# Settings the warnings to be ignored
warnings.filterwarnings('ignore')
  
# This warning won't display due to the disabled warnings
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?

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.

Similar Reads

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....

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:...

Disabling Python Warnings with Command

...