How to use filterwarnings() In Python

Warning messages are typically issued in situations where it is useful to alert the user of some condition in a program, where that condition (normally) doesn’t warrant raising an exception and terminating the program. To deal with warnings there is a built-in module called warning. To read more about python warnings you can check out this article

The filterwarnings() function can be used to control the behavior of warnings in your programs. The warnings filter controls whether warnings are ignored, displayed, or turned into errors (raising an exception). This can be done using different actions:

  • “ignore” to never print matching warnings
  • “error” to turn matching warnings into exceptions
  • “once” to print only the first occurrence of matching warnings, regardless of location

Syntax:

warnings.filterwarnings(action, message=”, category=Warning, module=”, lineno=0, append=False)

Example: Fixing warning using filterwarnings()

Python3




import numpy as np
import warnings
  
# suppress warnings
warnings.filterwarnings('ignore')
  
x = 789
x = np.float128(x)
print(np.exp(x))


Output:

using filterwarnings()



How to Fix: RuntimeWarning: Overflow encountered in exp

In this article we will discuss how to fix RuntimeWarning: overflow encountered in exp in Python.

This warning occurs while using the NumPy library’s exp() function upon using on a value that is too large. This function is used to calculate the exponential of all elements in the input array or an element (0-D Array of NumPy).

Example: Code to depict warning

Python3




import numpy as np
  
print(np.exp(789))


Output:

The output is infinity cause e^789 is a very large value 

This warning occurs because the maximum size of data that can be used in NumPy is float64 whose maximum range is 1.7976931348623157e+308. Upon taking logarithm its value becomes 709.782. For any larger value than this, the warning is generated.

Let us discuss ways to fix this.

Similar Reads

Method 1: Using float128

...

Method 2: Using filterwarnings()

The data type float64 can be changed to float128....