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
Python Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read