Warnings are provided to warn the developer of situations that aren't necessarily exceptions. Usually, a warning occurs when there is some obsolete of certain programming elements, 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 message, but the program runs. The
warn()
function defined in the '
warning
' module is used to show warning messages. The warning module is actually a subclass of Exception which is a built-in class in Python.
Python3
# program to display warning a message
import warnings
print('Geeks')
# displaying the warning message
warnings.warn('Warning Message: 4')
print('Geeks !')
Output:
Geeks
main.py:8: UserWarning: Warning Message: 4
warnings.warn('Warning Message: 4')
Geeks!
In the above program, the
warn()
function of the warning module is used to display the message
Warning: Message: 4
, the
UserWarning
is the default category of
warn()
function.
Warning Categories
In Python there are a variety of built-in exceptions which reflect categories of warning, some of them are:
- Warning Class: It is the super class of all warning category classes and a subclass of the Exception class.
- UserWarning Class: warn() function default category.
- DeprecationWarning Class: Base category for alerts regarding obsolete features when those warnings are for other developers (triggered by code in __main__ unless ignored).
- SyntaxWarning Class: Base class for warnings of suspicious syntactic attributes.
- RuntimeWarning Class: Base class for warnings of suspicious run time attributes.
- FutureWarning Class: Base class for warnings on obsolete features when certain warnings are meant for end-users of Python-written programs.
- PendingDeprecationWarning Class: Base class for warnings of an outdated attribute.
- ImportWarning Class: Base class for warnings caused during a module importation process.
- UnicodeWarning Class: Base class for Unicode based warnings.
- BytesWarning Class: Base class for bytes and bytearray based warnings.
- ResourceWarning Class: Base class for resource-related warnings.
Warning Filters
The warning filter in Python handles warnings (presented, disregarded or raised to exceptions). The warnings filter establishes an organized list of filter parameters, any particular warnings are matched on each filter requirement throughout the list till the match is made, the filter determines the match arrangement. Every entry is indeed a tuple (action, message, category, module, lineno) of the form in which:
- The action can be any of the following strings:
String |
Explanation |
"default" |
Displays the first matching warnings for each position |
"error" |
Converts warnings to raise exceptions |
"ignore" |
Never display warnings which match |
"always" |
Always display the warnings which match |
"module" |
Displays the first matching warnings per module |
"once" |
Display just the first matching warnings, regardless of where they are located |
- The message is a string that has a regular expression that must match the beginning of the warning. (The expression compiled is always case-insensitive)
- The category is a class (warning subclass) of which the warning class must be a subclass for matching.
- The module is a string with a regular expression which must match the module name (The expression compiled is always case-insensitive).
- The lineno is an integer to match the number of the line in which the warning appeared, or 0 to match any number of the line.
Warning Functions
Some of the commonly used functions of the warning module are:
- warn(message, category=None, stacklevel=1, source=None): This function displays a warning, or disregard it or converts is to an exception.
Python3
# program to illustrate warn()
# function in warning module
# importing modules
import warnings
# displaying warning
warnings.warn('Geeks 4 Geeks')
Output:
main.py:2: UserWarning: Geeks 4 Geeks
warnings.warn('Geeks 4 Geeks')
In the above program warnings are displayed using the warn()
function of warning module.
- warn_explicit(message, category, filename, lineno, module=None, registry=None, module_globals=None, source=None): This function is a low-level method with warn() features
- filterwarnings(action, message='', category=Warning, module='', lineno=0, append=False): This function adds an entry into the specifications of the warnings filter.
Python3
# program to illustrate filterwarnings()
# function in warning module
# importing module
import warnings
# adding entry into the specifications
# of the warnings filter.
warnings.filterwarnings('ignore', '.*do not.*', )
# displaying warinings
warnings.warn('Geeks 4 Geeks !')
# this warning will not be displayed
warnings.warn('Do not show this message')
Output:
main.py:8: UserWarning: Geeks 4 Geeks!
warnings.warn('Geeks 4 Geeks!')
Here the second warning message is not displayed due to warnings.filterwarnings('ignore', '.*do not.*', )
in which action is "ignore"
.
- showwarning(message, category, filename, lineno, file=None, line=None): This function Writes a warning to a file.
- simplefilter(action, category=Warning, lineno=0, append=False): This function adds a single entry into the warnings filter requirements list.
Python3 1==
# program to illustrate simplefilter()
# function in warning module
# importing module
import warnings
# adding a single entry into warnings filter
warnings.simplefilter('error', UserWarning)
# displaying the warning
warnings.warn('This is a warning message')
Output:
Traceback (most recent call last):
File "main.py", line 8, in
warnings.warn('This is a warning message')
UserWarning: This is a warning message
In the above program, a single entry is added to the warnings filter using warnings.simplefilter('error', UserWarning)
in which the action is "error"
and category is UserWrning
and then the warning is displayed using the warn()
method.
Similar Reads
How to Disable Python Warnings?
Python warnings are non-fatal messages that alert the user to potential problems in the code. Unlike exceptions, warnings do not interrupt the execution of the program, but they notify the user that something might not be working as expected. Warnings can be generated by the interpreter or manually
3 min read
Python String
A string is a sequence of characters. Python treats anything inside quotes as a string. This includes letters, numbers, and symbols. Python has no character data type so single character is a string of length 1.Pythons = "GfG" print(s[1]) # access 2nd char s1 = s + s[0] # update print(s1) # printOut
6 min read
Python | Issue Warning Message
Problem - To have a program that can issue warning messages (e.g., about deprecated features or usage problems). Code #1 : Use the warnings.warn() function Python3 1== import warnings def func(x, y, logfile = None, debug = False): if logfile is not None: warnings.warn('logfile argument deprecated',
2 min read
Python Variables
In Python, variables are used to store data that can be referenced and manipulated during program execution. A variable is essentially a name that is assigned to a value. Unlike many other programming languages, Python variables do not require explicit declaration of type. The type of the variable i
6 min read
Truthy in Python
In Python Programming, every value is either evaluated as True or False. Any value that is evaluated as a True boolean type is considered Truthy. The bool() function is used to check the Truthy or Falsy of an object. We will check how Python evaluates the truthiness of a value within a conditional s
1 min read
What is Python Leo
Python Leo is an innovative text editor and outliner that integrates seamlessly with the Python programming language, providing a powerful environment for project management, code development, and document organization. Leo, which stands for "Literate Editor with Outlines," combines the flexibility
3 min read
Variable Shadowing in Python
In this article, we will understand the concept of variable shadowing in a Python programming language. To understand this concept, we need to be well versed with the scope of a lifetime of variables in python. Local variables:When we define a function, we can create variables that are scoped only t
3 min read
Python Version History
Python, one of the most popular programming languages today, has a rich history of development and evolution. From its inception in the late 1980s to its current status as a versatile and powerful language, Python's version history reflects the language's adaptability and the community's dedication
5 min read
Working with Strings in Python 3
In Python, sequences of characters are referred to as Strings. It used in Python to record text information, such as names. Python strings are "immutable" which means they cannot be changed after they are created.Creating a StringStrings can be created using single quotes, double quotes, or even tri
5 min read
Triple Quotes in Python
In Python, triple quotes let us write strings that span multiple lines, using either three single quotes (''') or three double quotes ("""). While theyâre most often used in docstrings (the text that explains how code works), they also have other features that can be used in a variety of situations
2 min read