Warning control in Python Programs


Warning is different from error in a program. If error is encountered, Python program terminates instantly. Warning on the other hand is not fatal. It displays certain message but program continues. Warnings are issued to alert the user of certain conditions which aren't exactly exceptions. Typically warning appears if some deprecated usage of certain programming element like keyword/function/class etc. is found.

Warning messages are displayed by warn() function defined in 'warning' module of Python's standard library. Warning is actually a subclass of Exception in built-in class hierarchy. There are a number of built-in Warning subclasses. User defined subclass can also be defined.

Warning
 This is the base class of all warning category classes.
UserWarning
 The default category for warn().
DeprecationWarning
 warnings about deprecated features when those warnings are intended for developers
SyntaxWarning
 warnings about dubious syntactic features.
RuntimeWarning
warnings about dubious runtime features.
FutureWarning
 warnings about deprecated features when those warnings are intended for end users.
PendingDeprecationWarning
warnings about features that will be deprecated in the future
ImportWarning
 warnings triggered during the process of importing a module
UnicodeWarning
warnings related to Unicode.
BytesWarning
 warnings related to bytes and byte array.
ResourceWarning
 warnings related to resource usage.

Warning example

Following code defines a class with a deprecated method and a method scheduled to be deprecated in a future version of the said class.

# warningexample.py
import warnings
class WarnExample:
   def __init__(self):
      self.text = "Warning"

def method1(self):
   warnings.warn(
      "method1 is deprecated, use new_method instead",
      DeprecationWarning
   )
   print ('method1', len(self.text))
   def method2(self):
      warnings.warn(
         "method2 will be deprecated in version 2, use new_method instead",
         PendingDeprecationWarning
      )
      print ('method2', len(self.text))
   def new_method(self):
   print ('new method', len(self.text))
if __name__=='__main__':
   e = WarnExample()
   e.method1()
   e.method2()
   e.new_method()

If above script is executed from command prompt as

E:\python37>python warningexample.py

No warning messages are displayed on terminal. For that you have to use _Wd switch as below

E:\python37>python -Wd warningexample.py
warningexample.py:10: DeprecationWarning: method1 is deprecated, use new_method instead
DeprecationWarning
method1 7
warningexample.py:19: PendingDeprecationWarning: method2 will be deprecated in version 2, use new_method instead
PendingDeprecationWarning
method2 7
new method 7

Similarly, following interactive session too doesn't show any warning messages.

E:\python37>python
>>> from warningexample import WarnExample
>>> e = WarnExample()
>>> e.method1()
method1 7
>>> e.method2()
method2 7
>>> e.new_method()
new method 7

You have to start Python session with –Wd

E:\python37>python -Wd
>>> from warningexample import WarnExample
>>> e=WarnExample()
>>> e.method1()
E:\python37\warningexample.py:10: DeprecationWarning: method1 is deprecated, use new_method instead
DeprecationWarning
method1 7
>>> e.method2()
E:\python37\warningexample.py:17: PendingDeprecationWarning: method2 will be deprecated in version 2, use new_method instead
PendingDeprecationWarning
method2 7
>>> e.new_method()
new method 7

Warnings Filters

The warnings filter controls whether warnings are ignored, displayed, or turned into errors (raising an exception).

Action
Meaning
error
Turn the warning into an exception.
ignore
Discard the warning.
always
Always emit a warning.
default
Print the warning the first time it is generated from each location.
module
Print the warning the first time it is generated from each module.
once
Print the warning the first time it is generated.

Following interactive session sets filter to default by simplefilter() function.

E:\python37>python
>>> import warnings
>>> warnings.simplefilter('default')
>>> from warningexample import WarnExample
>>> e=WarnExample()
>>> e.method1()
E:\python37\warningexample.py:10: DeprecationWarning: method1 is deprecated, use new_method instead
DeprecationWarning
method1 7
>>> e.method2()
E:\python37\warningexample.py:17: PendingDeprecationWarning: method2 will be deprecated in version 2, use new_method instead
PendingDeprecationWarning
method2 7
>>> e.new_method()
new method 7

In order to temporarily suppress warnings, set simplefilter to 'ignore'.

import warnings

def function():
warnings.warn("deprecated", DeprecationWarning)

with warnings.catch_warnings():
warnings.simplefilter("ignore")
function()

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements