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.
We'll now explain the usage of these methods with simple examples one by one.
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.
Below are important parameters of the warn() method which needs to be set in order for the method to work properly.
A full list of warning categories is available here
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.
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
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.
Below we have provides important parameters of warn_explicit() method.
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.
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
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.
Below is a list of important parameters of showwarning() method which can be changed as per requirements.
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.
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)
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.
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
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.
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)
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
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.
Each filer has the below mentioned five values.
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.
Below we have included an explanation of the parameters of method simplefilter().
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.
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
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.
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
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.
Below we have mentioned a list of parameters of filterwarnings().
We have created 3 files to explain the usage of filterwarnings() method.
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.
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)
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
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
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.
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
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.
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.
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.
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.
If you are more comfortable learning through video tutorials then we would recommend that you subscribe to our YouTube channel.
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.
If you want to