Updated On : Jan-16,2021 Time Investment : ~25 mins

warnings - Simple Guide to Handle Warnings Messages in Python

Warnings messages are generally raised when the situation is not that worse that the program should be terminated. It's generally raised to alert programmers. For example, a programmer might call some function whose signature is changing in the future or method is going to be deprecated. Python provides a module named warnings which lets us works with warnings. It lets us raise warnings, filter warnings, format warnings, etc. It even let us change warnings into errors when the situation arises like making a program fail which is still using some old obsolete version of code that must be changed now. The warnings module by default directs all warnings messages to sys.stderr. It provides methods that can let us direct warnings messages to other mediums as well. The warnings module also provides us with filters that let us filter warnings messages and prevent them from printing repeatedly. It provides very fine-grained control over warnings. All the warnings available by default are a subclass of Warning class which itself is a subclass of Exception class. Even though warnings are subclasses of Exception, it does not halt the program until explicitly asked to do so. As a part of this tutorial, we'll explore the API of the warnings module with simple examples to make it easy to grasp.

We have below-highlighted methods available with the module that we'll explain with examples. We have grouped methods according to their usage.

  • Methods to Create Warnings - These methods are used to raise warnings.
    • warn()
    • warn_explicit()
  • Methods to Write Warnings to a File - These methods are used to write warnings messages to medium other than sys.stderr.
    • showwarning()
    • formatwarning()
  • Methods to Filter Warnings - These methods are used to filter warnings that might not need to be printed.
    • filterwarnings()
    • simplefilter()
  • Method to Reset Warnings - This method is used to reset warnings filters.
    • resetwarnings()
  • Context Manager for Testing Purposes - This method is used to capture warnings in a context and format them later.
    • catch_warnings()

We'll now explain the usage of these methods with simple examples one by one.

Example 1: Raise Deprecation Warning Using warn()

As a part of this example, we'll explain how we can use warn() method to raise warning messages. We have created simple script which calls 2 functions (addition() and add()) to add numbers. The function addition() can accept only two numbers to be added and obsolete whereas add() function can add as many numbers given as an argument to it. We have raised a deprecation warning from addition() function with the message that the function is deprecated and should not be used going forward as it'll be removing in future releases from the code.

warn() Parameters

Below are important parameters of the warn() method which needs to be set in order for the method to work properly.

  • message - It accepts a string message that will be printed when this warning is raised.
  • category - This parameter accepts any of the Warning category (a subclass of Warning) from the list of available warnings with python. If not provided warning of type Warning will be raised.
  • stacklevel - It accepts an integer argument that specifies which method should be printed in the warning message. The default value is 1. It'll print method named in which it’s called. If we give the value of 2 then it'll go one level up and print the caller of the method.

A full list of warning categories is available here

warnings_example_1.py
import warnings

def addition(a, b):
    warnings.warn(message = "Addition Function is Deprecated and will be removed in future release. Please use add() Function instead.",
                  category=DeprecationWarning)

    return a + b

def add(*args):
    return sum(args)

if __name__ == "__main__":
    out1 = addition(1,2)

    print("\nAddition Function Output : ", out1)

    out2 = add(1, 2, 3, 4)

    print("\nAdd Function Output      : ", out2)

OUTPUT

warnings_example_1.py:5: DeprecationWarning: Addition Function is Deprecated and will be removed in future release. Please use add() Function instead.
  category=DeprecationWarning)

Addition Function Output :  3

Add Function Output      :  10

Below we have again written script with only one minor change that we have included stacklevel argument with a value of 2 in our code. We can see that now the output is including a line of our code where the method is getting called.

warnings_example_1.py
import warnings

def addition(a, b):
    warnings.warn(message = "Addition Function is Deprecated and will be removed in future release. Please use add() Function instead.",
                  category=DeprecationWarning, stacklevel=2)

    return a + b

def add(*args):
    return sum(args)

if __name__ == "__main__":
    out1 = addition(1,2)

    print("\nAddition Function Output : ", out1)

    out2 = add(1, 2, 3, 4)

    print("\nAdd Function Output      : ", out2)

OUTPUT

warnings_example_1.py:13: DeprecationWarning: Addition Function is Deprecated and will be removed in future release. Please use add() Function instead.
  out1 = addition(1,2)

Addition Function Output :  3

Add Function Output      :  10

Example 2: Raise Deprecation Warning Using warn_explicit()

As a part of our second example, we'll explain the usage of warn_explicit() method. It works almost like warn() method but provides more control over warning. It let us specify the filename, line number, and module of the warnings.

warn_explicit() Parameters

Below we have provides important parameters of warn_explicit() method.

  • message - It accepts a string message that will be printed when this warning is raised.
  • category - This parameter accepts any of the Warning category (a subclass of Warning) from the list of available warnings with python. If not provided warning of type Warning will be raised.
  • filename - It accepts filename where a warning has occurred.
  • lineno - It accepts the line number of the method which has a warning.
  • module - It accepts the module name of the code that has a warning.

Our second example code is almost the same as the first example with the only difference being that we have used warn_explicit() to raise warning instead of warn(). We have specified filename as name so that it takes filename directly and line no as 3 because method addition starts at 3rd line.

warnings_example_2.py
import warnings

def addition(a, b):
    warnings.warn_explicit(message = "Addition Function is Deprecated and will be removed in future release. Please use add() Function instead.",
                  category=DeprecationWarning,
                  filename=__name__,
                  lineno=3,
                  )

    return a + b

def add(*args):
    return sum(args)

if __name__ == "__main__":
    out1 = addition(1,2)

    print("\nAddition Function Output : ", out1)

    out2 = add(1, 2, 3, 4)

    print("\nAdd Function Output      : ", out2)

OUTPUT

__main__:3: DeprecationWarning: Addition Function is Deprecated and will be removed in future release. Please use add() Function instead.

Addition Function Output :  3

Add Function Output      :  10

Example 3: Print Deprecation Warning Using showwarning()

As a part of our third example, we'll demonstrate how we can use showwarning() method to direct warnings to sys.stdout instead of default sys.stderr. This method also lets us direct warning messages to a file if needed.

In this example, we have used code same as our previous examples with minor changes. We'll be using the same example with changes for all examples of our tutorial. We have moved the code for method addition() and add() to a file named addition.py. We have kept our remaining original code in a file named warnings_example_3.py. We are calling addition() and add() method to be importing the addition module. We have kept code for showwarning() in addition() method.

showwarning() Parameters

Below is a list of important parameters of showwarning() method which can be changed as per requirements.

  • message - It accepts a string message that will be printed when this warning is raised.
  • category - This parameter accepts any of the Warning category (a subclass of Warning) from the list of available warnings with python. If not provided warning of type Warning will be raised.
  • filename - It accepts filename where a warning has occurred.
  • lineno - It accepts the line number of the method which has a warning. This line text will be printed in a warning message if we have not explicitly provided line parameter.
  • file - It accepts file name where warning messages will be directed. It can even accept sys.stdout and will direct messages to standard output. By default this parameter has None value and messages will be directed to sys.stderr.
  • line - This parameter accepts a string which is the line that will be printed along with the error message. This parameter is None by default and code at line lineno in file filename will be included in the message.

We can see from the output below that we have not provided line parameter value hence it's printing line number 4 of addition.py in the warning message. We have directed a warning message to sys.stdout.

addition.py
import warnings
import sys

def addition(a, b):
    warnings.showwarning(message = "Addition Function is Deprecated and will be removed in future release. Please use add() Function instead.",
                         category=DeprecationWarning,
                         filename=__name__ + ".py",
                         lineno=4,
                         file=sys.stdout
                  )

    return a + b

def add(*args):
    return sum(args)
warnings_example_3.py
import addition

if __name__ == "__main__":
    out1 = addition.addition(1,2)

    print("\nAddition Function Output : ", out1)

    out2 = addition.add(1, 2, 3, 4)

    print("\nAdd Function Output      : ", out2)

OUTPUT

addition.py:4: DeprecationWarning: Addition Function is Deprecated and will be removed in future release. Please use add() Function instead.
  def addition(a, b):

Addition Function Output :  3

Add Function Output      :  10

Below we have modified our code of addition.py a little but where we have provided string for line parameter. We can notice from the output that the warning message has now a string from that parameter and not retrieved from a combination of filename and lineno parameters like earlier.

addition.py
import warnings
import sys

def addition(a, b):
    warnings.showwarning(message = "Addition Function is Deprecated and will be removed in future release. Please use add() Function instead.",
                  category=DeprecationWarning,
                  filename=__name__ + ".py",
                  lineno=4,
                  file=sys.stdout,
                  line="Addition Function With Two Arguments"
                  )

    return a + bAddition Function With Two Arguments

def add(*args):
    return sum(args)

OUTPUT

addition.py:4: DeprecationWarning: Addition Function is Deprecated and will be removed in future release. Please use add() Function instead.
  Addition Function With Two Arguments

Addition Function Output :  3

Add Function Output      :  10

Example 4: Print Deprecation Warning Using formatwarning()

As a part of our sixth example, we'll demonstrate usage of formatwarning() method. This method has the same format and usage as that of showwarning()but it returns a warning message as a string instead of printing it. This can be useful if we don't want to print a warning message at that time and have a different plan of handling it.

We have kept code for addition() and add() methods in a different file named addition_modified.py like earlier. We are calling formatwarning() in addition() method and storing its output in a variable named warning_result. We are then printing warning_result. Our rest of the code which calls these two methods is kept in warnings_example_4.py file.

addition_modified.py
import warnings
import sys

def addition(a, b):
    warning_result = warnings.formatwarning(message = "Addition Function is Deprecated and will be removed in future release. Please use add() Function instead.",
                  category=DeprecationWarning,
                  filename=__name__ + ".py",
                  lineno=4,
                  line="Addition Function With Two Arguments"
                  )

    print("Inside addition(%d, %d)"%(a,b))
    print("\n",warning_result)

    return a + b

def add(*args):
    return sum(args)
warnings_example_4.py
import addition_modified

if __name__ == "__main__":
    out1 = addition_modified.addition(1,2)

    print("\nAddition Function Output : ", out1)

    out2 = addition_modified.add(1, 2, 3, 4)

    print("\nAdd Function Output      : ", out2)

OUTPUT

Inside addition(1, 2)

 addition_modified.py:4: DeprecationWarning: Addition Function is Deprecated and will be removed in future release. Please use add() Function instead.
  Addition Function With Two Arguments


Addition Function Output :  3

Add Function Output      :  10

Example 5: Filter All Warnings Using simplefilter()

As a part of our fifth example, we'll demonstrate the usage of simplefilter() method which can be used to filter and remove some of the warning messages from all that will be printed. If our code is repeatedly calling some method that is obsolete then the output will be flooded with warning messages. We want to prevent this and want a warning message to be raised once. This can be done using simplefilter() method. This method lets us filter all warning messages rather than filtering warning messages of a particular module or file.

The filter is defined as a tuple of five values in warnings. When a warning is raised, it’s matched with conditions of filters one by one from the list of filters until a match is found. If we found a match with a filter then that warning will be suppressed else the default action is applied as explained below in filter values. We can access the list of filters which currently set at any point by calling filters attribute of the warnings module and it'll return a list of filters where individual entry is a tuple of 5 values explaining that filter.

Warning Filter Values Explanation

Each filer has the below mentioned five values.

  • action - It holds one of the following string specifying how to filter warning messages. Below is a list of possible string values for action.
    • default - It prints the first matching occurrence of warning (module + line no). It warning raised for the combination of module and line number will be printed only once.
    • error - It'll convert warning into error and halt program execution. This can be useful if we want to stop programmers from using a particular code. The failure will force them to switch from it.
    • ignore - This will ignore all warnings which match this filter’s conditions.
    • always - This will print all warnings which match this filter’s conditions.
    • module - This will print the first occurrence of warning for each module and line number.
    • once - This will print the first occurrence of warning only regardless of the line number.
  • message - It holds a string with a regular expression that matches the warning message.
  • category - It holds a reference to one of a subclass of Warning or Warning itself.
  • module - It holds a string that has a regular expression for matching the module name. This is set with a regular expression when we want to filter warning messages of a particular module of a bunch of modules rather than all warning messages.
  • lineno - This holds integer value specifying line number where the warning occurred must match. If it has 0 value then all lines are matched else specific line of the file is matched and a warning raised from that line is filtered.

Our code below has same methods addition() and add() like earlier where addition() method raises future warning. Our code first loops through a list of filters and prints them. It then calls addition() method and adds a new filter that filters all future warnings from all modules. We are then printing all filters again and calling addition() method again to check whether the warning raised by it is suppressed after adding the filter.

simplefilter() Parameters

Below we have included an explanation of the parameters of method simplefilter().

  • action - We specify one of the strings mentioned above in action filter values for this parameter.
  • category - This parameter accepts any of the Warning category (a subclass of Warning) from the list of available warnings with python. It has the default value Warning.
  • lineno - It accepts integer value specifying line number where warning must match. If we specify 0 then all lines of a file are considered and filtered else only warning occurred from the line number mentioned is filtered.
  • append - This parameter accepts boolean value specifying whether the filter created by this method should be appended at the end of the list of filters or not. By default simplefilter() method inserts a filter at the beginning of the list.

We can see from the output when we run the script below that after we have introduced a new future warning filter, a list of filters has an entry for it, and a warning raised by addition() method is suppressed as well.

warnings_example_5.py
import warnings

def addition(a, b):
    warnings.warn(message = "Addition Function is Deprecated and will be removed in future release. Please use add() Function instead.", category=FutureWarning)

    return a + b

def add(*args):
    return sum(args)

if __name__ == "__main__":

    print("Warning Filters (Before Calling SimpleFilter) : ")
    for fltr in warnings.filters:
        print(fltr)
    print()

    out1 = addition(1,2)

    print("\nAddition Function Output (Before Introducing Filter) : ", out1)

    warnings.simplefilter("ignore", FutureWarning, lineno=0)

    print("="*100)
    print("\nWarning Filters (After Calling SimpleFilter) : ")
    for fltr in warnings.filters:
        print(fltr)

    out1 = addition(1,2)

    print("\nAddition Function Output (After Introducing Filter) : ", out1)

    out2 = add(1, 2, 3, 4)

    print("\nAdd Function Output      : ", out2)

OUTPUT

Warning Filters (Before Calling SimpleFilter) :
('default', None, <class 'DeprecationWarning'>, '__main__', 0)
('ignore', None, <class 'DeprecationWarning'>, None, 0)
('ignore', None, <class 'PendingDeprecationWarning'>, None, 0)
('ignore', None, <class 'ImportWarning'>, None, 0)
('ignore', None, <class 'ResourceWarning'>, None, 0)

warnings_example_5.py:4: FutureWarning: Addition Function is Deprecated and will be removed in future release. Please use add() Function instead.
  warnings.warn(message = "Addition Function is Deprecated and will be removed in future release. Please use add() Function instead.", category=FutureWarning)

Addition Function Output (Before Introducing Filter) :  3
====================================================================================================

Warning Filters (After Calling SimpleFilter) :
('ignore', None, <class 'FutureWarning'>, None, 0)
('default', None, <class 'DeprecationWarning'>, '__main__', 0)
('ignore', None, <class 'DeprecationWarning'>, None, 0)
('ignore', None, <class 'PendingDeprecationWarning'>, None, 0)
('ignore', None, <class 'ImportWarning'>, None, 0)
('ignore', None, <class 'ResourceWarning'>, None, 0)

Addition Function Output (After Introducing Filter) :  3

Add Function Output      :  10

Example 6: Filter Warning at Particular Line Number Using simplefilter()

As a part of our sixth example, we are again demonstrating usage of simplefilter() method. The code is almost the same as the last example with minor changes. First, we have changed the value of lineno parameter from 0 to 4 in method simplefilter(). This change will add a filter that will only filter FutureWarning which occurs at line number 4 from any module.

We have created two version of addition() method (addition1() and addition2()). Both raise a future warning message. We are calling both methods for calculating the addition of two numbers before the introduction of the filter and after. We are also printing a list of filters before and after the addition of filters for verification purposes.

We can see from the output that it is a filtering warning message raised by addition1() method only and not the one raised by addition2() after the introduction of the filter.

warnings_example_6.py
import warnings

def addition1(a, b):
    warnings.warn(message = "Addition Function is Deprecated and will be removed in future release. Please use add() Function instead.", category=FutureWarning)

    return a + b

def addition2(a, b):
    warnings.warn(message = "Addition Function is Deprecated and will be removed in future release. Please use add() Function instead.", category=FutureWarning)

    return a + b

def add(*args):
    return sum(args)

if __name__ == "__main__":

    print("Warning Filters (Before Calling SimpleFilter) : ")
    for fltr in warnings.filters:
        print(fltr)
    print()

    out1 = addition1(1,2)

    print("\nAddition1 Function Output (Before Introducing Filter) : ", out1, "\n")

    out1 = addition2(1,2)

    print("\nAddition2 Function Output (Before Introducing Filter) : ", out1)

    warnings.simplefilter("ignore", FutureWarning, lineno=4)

    print("="*100)
    print("\nWarning Filters (After Calling SimpleFilter) : ")
    for fltr in warnings.filters:
        print(fltr)

    out1 = addition1(1,2)

    print("\nAddition1 Function Output (After Introducing Filter) : ", out1, "\n")

    out1 = addition2(1,2)

    print("\nAddition2 Function Output (After Introducing Filter) : ", out1)

    out2 = add(1, 2, 3, 4)

    print("\nAdd Function Output      : ", out2)

OUTPUT

Warning Filters (Before Calling SimpleFilter) :
('default', None, <class 'DeprecationWarning'>, '__main__', 0)
('ignore', None, <class 'DeprecationWarning'>, None, 0)
('ignore', None, <class 'PendingDeprecationWarning'>, None, 0)
('ignore', None, <class 'ImportWarning'>, None, 0)
('ignore', None, <class 'ResourceWarning'>, None, 0)

warnings_example_6.py:4: FutureWarning: Addition Function is Deprecated and will be removed in future release. Please use add() Function instead.
  warnings.warn(message = "Addition Function is Deprecated and will be removed in future release. Please use add() Function instead.", category=FutureWarning)

Addition1 Function Output (Before Introducing Filter) :  3

warnings_example_6.py:9: FutureWarning: Addition Function is Deprecated and will be removed in future release. Please use add() Function instead.
  warnings.warn(message = "Addition Function is Deprecated and will be removed in future release. Please use add() Function instead.", category=FutureWarning)

Addition2 Function Output (Before Introducing Filter) :  3
====================================================================================================

Warning Filters (After Calling SimpleFilter) :
('ignore', None, <class 'FutureWarning'>, None, 4)
('default', None, <class 'DeprecationWarning'>, '__main__', 0)
('ignore', None, <class 'DeprecationWarning'>, None, 0)
('ignore', None, <class 'PendingDeprecationWarning'>, None, 0)
('ignore', None, <class 'ImportWarning'>, None, 0)
('ignore', None, <class 'ResourceWarning'>, None, 0)

Addition1 Function Output (After Introducing Filter) :  3

warnings_example_6.py:9: FutureWarning: Addition Function is Deprecated and will be removed in future release. Please use add() Function instead.
  warnings.warn(message = "Addition Function is Deprecated and will be removed in future release. Please use add() Function instead.", category=FutureWarning)

Addition2 Function Output (After Introducing Filter) :  3

Add Function Output      :  10

Example 7: FIlter Warnings Of Particular Module Using filterwarnings()

As a part of our seventh example, we'll demonstrate usage of filterwarnings() method. This method also like the simplefilter() is used to add a new filter to the list of filters. The MAJOR difference between this method and simplefilter() is that this method provides finer control on filtering warning messages that let us filter warning of particular module whereas simplefilter() works on all modules. It even let us match warning message with a regular expression for filtering.

filterwarnings() Parameters

Below we have mentioned a list of parameters of filterwarnings().

  • action - Same meaning as simplefilter().
  • category - Same meaning as simplefilter().
  • lineno - Same meaning as simplefilter().
  • append - Same meaning as simplefilter().
  • message - This parameter accepts a string and all warning messages which has this string will be filtered.
  • module - This parameter accepts a string and warning messages raised from all modules which have this string in its name will be suppressed.

We have created 3 files to explain the usage of filterwarnings() method.

  • addition1.py - It has definition of method addition1() and add(). The addition1() method raised future warning.
  • addition2.py - It has the definition of addition2() method which raises a future warning.
  • warnings_example_7.py - It has code that first prints a list of existing filters. It then calls addition1() and addition2() methods. After that, it creates a filter using filterwarnings() and prints a list of filters again. At last, it calls addition1() and addition2() methods again.

When we run script warnings_example_7.py, we can notice from the output that the warning raised by addition1() method is suppressed. Please make a note that warning is mentioned at line number 4 in both addition1.py and addition2.py file but only the warning raised by addition1.py file is filtered. The reason for this is because we have set the module parameter of filterwarnings() to string addition1.

addition1.py
import warnings

def addition1(a, b):
    warnings.warn(message = "Addition Function is Deprecated and will be removed in future release. Please use add() Function instead.", category=FutureWarning)

    return a + b


def add(*args):
    return sum(args)
addition2.py
import warnings

def addition2(a, b):
    warnings.warn(message = "Addition Function is Deprecated and will be removed in future release. Please use add() Function instead.", category=FutureWarning)

    return a + b
warnings_example_7.py
import addition1, addition2
import warnings

if __name__ == "__main__":

    print("Warning Filters (Before Calling SimpleFilter) : ")
    for fltr in warnings.filters:
        print(fltr)
    print()

    out1 = addition1.addition1(1,2)

    print("\nAddition1 Function Output (Before Introducing Filter) : ", out1, "\n")

    out1 = addition2.addition2(1,2)

    print("\nAddition2 Function Output (Before Introducing Filter) : ", out1)

    warnings.filterwarnings("ignore", category=FutureWarning, lineno=4, module="addition1")
    #warnings.filterwarnings("ignore", category=FutureWarning, lineno=0, module="addition1")

    print("="*100)
    print("\nWarning Filters (After Calling SimpleFilter) : ")
    for fltr in warnings.filters:
        print(fltr)

    out1 = addition1.addition1(1,2)

    print("\nAddition1 Function Output (After Introducing Filter) : ", out1, "\n")

    out1 = addition2.addition2(1,2)

    print("\nAddition2 Function Output (After Introducing Filter) : ", out1)

    out2 = addition1.add(1, 2, 3, 4)

    print("\nAdd Function Output      : ", out2)

OUTPUT

Warning Filters (Before Calling SimpleFilter) :
('default', None, <class 'DeprecationWarning'>, '__main__', 0)
('ignore', None, <class 'DeprecationWarning'>, None, 0)
('ignore', None, <class 'PendingDeprecationWarning'>, None, 0)
('ignore', None, <class 'ImportWarning'>, None, 0)
('ignore', None, <class 'ResourceWarning'>, None, 0)

/home/sunny/warnings_examples/addition1.py:4: FutureWarning: Addition Function is Deprecated and will be removed in future release. Please use add() Function instead.
  warnings.warn(message = "Addition Function is Deprecated and will be removed in future release. Please use add() Function instead.", category=FutureWarning)

Addition1 Function Output (Before Introducing Filter) :  3

/home/sunny/warnings_examples/addition2.py:4: FutureWarning: Addition Function is Deprecated and will be removed in future release. Please use add() Function instead.
  warnings.warn(message = "Addition Function is Deprecated and will be removed in future release. Please use add() Function instead.", category=FutureWarning)

Addition2 Function Output (Before Introducing Filter) :  3
====================================================================================================

Warning Filters (After Calling SimpleFilter) :
('ignore', None, <class 'FutureWarning'>, re.compile('addition1'), 4)
('default', None, <class 'DeprecationWarning'>, '__main__', 0)
('ignore', None, <class 'DeprecationWarning'>, None, 0)
('ignore', None, <class 'PendingDeprecationWarning'>, None, 0)
('ignore', None, <class 'ImportWarning'>, None, 0)
('ignore', None, <class 'ResourceWarning'>, None, 0)

Addition1 Function Output (After Introducing Filter) :  3

/home/sunny/warnings_examples/addition2.py:4: FutureWarning: Addition Function is Deprecated and will be removed in future release. Please use add() Function instead.
  warnings.warn(message = "Addition Function is Deprecated and will be removed in future release. Please use add() Function instead.", category=FutureWarning)

Addition2 Function Output (After Introducing Filter) :  3

Add Function Output      :  10

Example 8: Reset Warnings Using resetwarnings()

As a part of our eight example, we'll demonstrate how to use resetwarnings() method. This method clears all filters which are set by default and by the program.

Below we have created a simple script to explain the usage of resetwarnings() method. We are printing a list of filters at the beginning of the script. Then we are adding few filters using simplefilter() & filterwarnings() methods and printing a list of filters to check all filters are added properly. At last, we are calling resetwarnings() method and printing the list of filters again.

We can notice from the output that all filters are cleared by resetwarnings() method.

Please make a note that we have appended the last 2 filters of our 4 filters at the end of the list of filters by setting append parameter to True.

warnings_example_8.py
import warnings

if __name__ == "__main__":

    print("Warning Filters (Before Introducing Filters) : ")
    for fltr in warnings.filters:
        print(fltr)
    print()

    ## Introducing Filters
    warnings.simplefilter("ignore", FutureWarning, lineno=4)
    warnings.simplefilter("error", UnicodeWarning, lineno=0)
    warnings.simplefilter("error", BytesWarning, lineno=0, append=True)
    warnings.filterwarnings("module", category=FutureWarning, lineno=4, module="random", append=True, message="Future")

    print("="*100)
    print("\nWarning Filters (After Introducing Filters) : ")
    for fltr in warnings.filters:
        print(fltr)

    warnings.resetwarnings()

    print("="*100)
    print("\nWarning Filters (After Resetting Filters) : ")
    if warnings.filters:
        for fltr in warnings.filters:
            print(fltr)
    else:
        print("No Filters Present")

OUTPUT

Warning Filters (Before Introducing Filters) :
('default', None, <class 'DeprecationWarning'>, '__main__', 0)
('ignore', None, <class 'DeprecationWarning'>, None, 0)
('ignore', None, <class 'PendingDeprecationWarning'>, None, 0)
('ignore', None, <class 'ImportWarning'>, None, 0)
('ignore', None, <class 'ResourceWarning'>, None, 0)

====================================================================================================

Warning Filters (After Introducing Filters) :
('error', None, <class 'UnicodeWarning'>, None, 0)
('ignore', None, <class 'FutureWarning'>, None, 4)
('default', None, <class 'DeprecationWarning'>, '__main__', 0)
('ignore', None, <class 'DeprecationWarning'>, None, 0)
('ignore', None, <class 'PendingDeprecationWarning'>, None, 0)
('ignore', None, <class 'ImportWarning'>, None, 0)
('ignore', None, <class 'ResourceWarning'>, None, 0)
('error', None, <class 'BytesWarning'>, None, 0)
('module', re.compile('Future', re.IGNORECASE), <class 'FutureWarning'>, re.compile('random'), 4)
====================================================================================================

Warning Filters (After Resetting Filters) :
No Filters Present

Example 9: Turn Warning into Error using Filter

As a part of our ninth example, we are demonstrating how we can convert a warning to an error by setting the action parameter to error in simplefilter() method. Our code for this example is exactly the same as our fifth example with the only difference that we have set action in simplefilter() method to error instead of ignore. This will instruct the interpreter to raise errors when this warning happens.

Please make a note that we can perform the same functionality using filterwarnings() method as well.

warnings_example_9.py
import warnings

def addition(a, b):
    warnings.warn(message = "Addition Function is Deprecated and will be removed in future release. Please use add() Function instead.", category=FutureWarning)

    return a + b

def add(*args):
    return sum(args)

if __name__ == "__main__":

    print("Warning Filters (Before Calling SimpleFilter) : ")
    for fltr in warnings.filters:
        print(fltr)
    print()

    out1 = addition(1,2)

    print("\nAddition Function Output (Before Introducing Filter) : ", out1)

    warnings.simplefilter("error", FutureWarning, lineno=4)

    print("="*100)

    print("\nWarning Filters (After Calling SimpleFilter) : ")
    for fltr in warnings.filters:
        print(fltr)
    print()

    out1 = addition(1,2)

    print("\nAddition Function Output (After Introducing Filter) : ", out1)

    out2 = add(1, 2, 3, 4)

    print("\nAdd Function Output      : ", out2)

OUTPUT

Warning Filters (Before Calling SimpleFilter) :
('default', None, <class 'DeprecationWarning'>, '__main__', 0)
('ignore', None, <class 'DeprecationWarning'>, None, 0)
('ignore', None, <class 'PendingDeprecationWarning'>, None, 0)
('ignore', None, <class 'ImportWarning'>, None, 0)
('ignore', None, <class 'ResourceWarning'>, None, 0)

warnings_example_9.py:4: FutureWarning: Addition Function is Deprecated and will be removed in future release. Please use add() Function instead.
  warnings.warn(message = "Addition Function is Deprecated and will be removed in future release. Please use add() Function instead.", category=FutureWarning)

Addition Function Output (Before Introducing Filter) :  3
====================================================================================================

Warning Filters (After Calling SimpleFilter) :
('error', None, <class 'FutureWarning'>, None, 4)
('default', None, <class 'DeprecationWarning'>, '__main__', 0)
('ignore', None, <class 'DeprecationWarning'>, None, 0)
('ignore', None, <class 'PendingDeprecationWarning'>, None, 0)
('ignore', None, <class 'ImportWarning'>, None, 0)
('ignore', None, <class 'ResourceWarning'>, None, 0)

Traceback (most recent call last):
  File "warnings_example_9.py", line 31, in <module>
    out1 = addition(1,2)
  File "warnings_example_9.py", line 4, in addition
    warnings.warn(message = "Addition Function is Deprecated and will be removed in future release. Please use add() Function instead.", category=FutureWarning)
FutureWarning: Addition Function is Deprecated and will be removed in future release. Please use add() Function instead.

Example 10: Using Context Manager to Test and Catch Warnings

As a part of our tenth and last example, we'll demonstrate how we can use context manager using catch_warnings() method to test a particular part of our code. The catch_warnings() provides a context manager that can wrap code without changing filters set outside of it. We can test code inside the context manager by introducing new filters and removing filters but it won't change the filter list outside of the context manager. We can also record warnings raised during context manager by setting record parameter of catch_warnings() method to True.

We have created a simple example below to explain the usage of context manager created using catch_warnings(). We have created a method named addition1() which adds two numbers and raises FutureWarning. We have created another method named addition2() which also adds two numbers and raises DeprecationWarning. Our main code first prints a list of filters and calls addition1() and addition2() methods. It then adds filters to ignore future warnings occurring at line number 4 to the list of filters. We then go on to create a context manager using catch_warnings(). Inside the context manager, we first clear all filters using resetwarnings() method, add the filter to ignore deprecation warnings occurring anywhere in code, and print a list of filters. Then we call addition1() and addition2() methods. At last, we use the context manager instance to print warnings raised. Once we are outside of the context manager, we again print a list of filters and call addition1() and addition2() methods.

We can notice from the output that when we first call addition1() and addition2() methods, both warning messages are printed. When we call both methods inside of context manager, only a warning message of addition1() is raised because inside context manager, we have created a deprecation warning suppress filter. Once we are out of context manager, we have again called both methods and we can see that warning message for method addition2() is printed because we have created a filter to ignore future warning occurring at line number 4 in the code.

warnings_example_10.py
import warnings

def addition1(a, b):
    warnings.warn(message = "Addition-1 Function is Deprecated and will be removed in future release. Please use add() Function instead.", category=FutureWarning)

    return a + b

def addition2(a, b):
    warnings.warn(message = "Addition-2 Function is Deprecated and will be removed in future release. Please use add() Function instead.", category=DeprecationWarning)

    return a + b

def add(*args):
    return sum(args)

if __name__ == "__main__":

    print("Warning Filters Initially : ")
    for fltr in warnings.filters:
        print(fltr)
    print()

    out1 = addition1(1,2)
    print("\nAddition1 Function Output (Initially) : ", out1, "\n")

    out1 = addition2(1,2)
    print("\nAddition2 Function Output (Initially) : ", out1)

    warnings.simplefilter("ignore", FutureWarning, lineno=4)

    print("="*100)

    with warnings.catch_warnings(record=True) as cx_manager:
        warnings.resetwarnings()

        warnings.simplefilter("ignore", DeprecationWarning, lineno=0)

        print("\nWarning Filters (Inside Context Manager) : ")
        for fltr in warnings.filters:
            print(fltr)

        out1 = addition1(1,2)
        print("\nAddition1 Function Output (Inside Context Manager) : ", out1)

        out1 = addition2(1,2)
        print("\nAddition2 Function Output (Inside Context Manager) : ", out1)

        print("\nContext Manage Warning Recordings : ", cx_manager)
        for w in cx_manager:
            print("Warning Category : ", w.category)
            print("Warning Message  : ", w.message)

    print("="*100)
    print("\nWarning Filters (Outside Context Manager) : ")
    for fltr in warnings.filters:
        print(fltr)


    out1 = addition1(1,2)
    print("\nAddition1 Function Output (Outside Context Manager) : ", out1, "\n")

    out1 = addition2(1,2)
    print("\nAddition2 Function Output (Outside Context Manager) : ", out1)

OUTPUT

Warning Filters Initially :
('default', None, <class 'DeprecationWarning'>, '__main__', 0)
('ignore', None, <class 'DeprecationWarning'>, None, 0)
('ignore', None, <class 'PendingDeprecationWarning'>, None, 0)
('ignore', None, <class 'ImportWarning'>, None, 0)
('ignore', None, <class 'ResourceWarning'>, None, 0)

warnings_example_10.py:4: FutureWarning: Addition-1 Function is Deprecated and will be removed in future release. Please use add() Function instead.
  warnings.warn(message = "Addition-1 Function is Deprecated and will be removed in future release. Please use add() Function instead.", category=FutureWarning)

Addition1 Function Output (Initially) :  3

warnings_example_10.py:9: DeprecationWarning: Addition-2 Function is Deprecated and will be removed in future release. Please use add() Function instead.
  warnings.warn(message = "Addition-2 Function is Deprecated and will be removed in future release. Please use add() Function instead.", category=DeprecationWarning)

Addition2 Function Output (Initially) :  3
====================================================================================================

Warning Filters (Inside Context Manager) :
('ignore', None, <class 'DeprecationWarning'>, None, 0)

Addition1 Function Output (Inside Context Manager) :  3

Addition2 Function Output (Inside Context Manager) :  3

Context Manage Warning Recordings :  [<warnings.WarningMessage object at 0x7f7e9153a7f0>]
Warning Category :  <class 'FutureWarning'>
Warning Message  :  Addition-1 Function is Deprecated and will be removed in future release. Please use add() Function instead.
====================================================================================================

Warning Filters (Outside Context Manager) :
('ignore', None, <class 'FutureWarning'>, None, 4)
('default', None, <class 'DeprecationWarning'>, '__main__', 0)
('ignore', None, <class 'DeprecationWarning'>, None, 0)
('ignore', None, <class 'PendingDeprecationWarning'>, None, 0)
('ignore', None, <class 'ImportWarning'>, None, 0)
('ignore', None, <class 'ResourceWarning'>, None, 0)

Addition1 Function Output (Outside Context Manager) :  3

warnings_example_10.py:9: DeprecationWarning: Addition-2 Function is Deprecated and will be removed in future release. Please use add() Function instead.
  warnings.warn(message = "Addition-2 Function is Deprecated and will be removed in future release. Please use add() Function instead.", category=DeprecationWarning)

Addition2 Function Output (Outside Context Manager) :  3

This ends our small tutorial explaining the usage of warnings API with simple examples. Please feel free to let us know your views in the comments section.

Sunny Solanki  Sunny Solanki

YouTube Subscribe Comfortable Learning through Video Tutorials?

If you are more comfortable learning through video tutorials then we would recommend that you subscribe to our YouTube channel.

Need Help Stuck Somewhere? Need Help with Coding? Have Doubts About the Topic/Code?

When going through coding examples, it's quite common to have doubts and errors.

If you have doubts about some code examples or are stuck somewhere when trying our code, send us an email at coderzcolumn07@gmail.com. We'll help you or point you in the direction where you can find a solution to your problem.

You can even send us a mail if you are trying something new and need guidance regarding coding. We'll try to respond as soon as possible.

Share Views Want to Share Your Views? Have Any Suggestions?

If you want to

  • provide some suggestions on topic
  • share your views
  • include some details in tutorial
  • suggest some new topics on which we should create tutorials/blogs
Please feel free to contact us at coderzcolumn07@gmail.com. We appreciate and value your feedbacks. You can also support us with a small contribution by clicking DONATE.


Subscribe to Our YouTube Channel

YouTube SubScribe

Newsletter Subscription