• Home
  • Blog
  • Python
  • Working with warnings in Python (Or: When is an exception not an exception?)

Working with warnings in Python (Or: When is an exception not an exception?)

April 27, 2020 . By Reuven

It happens to all of us: You write some Python code, but you encounter an error:

>>> for i in 10:    # this will not work!

TypeError: 'int' object is not iterable

This isn’t just an error, but an exception. It’s Python’s way of saying that there was a problem in a defined way, such that we can trap it using the “try” and “except” keywords.

Just like everything else in Python, an exception is an object. This means that an exception has a class — and it’s that class we use to trap the exception:

    for i in 10:
except TypeError as e:
    print(f'Problem with your "for" loop: {e}')

We can even have several “except” clauses, each of which looks for a different type of error. But every Python class (except for “object”) inherits from some other class, and that’s true for exception classes, as well. So if we want to trap both “KeyError” and “IndexError”, then we could name them both explicitly. Or we could just trap “LookupError”, the parent class of both “KeyError” and “IndexError”.

Python’s exception-class hierarchy is visible at https://docs.python.org/3/library/exceptions.html#exception-hierarchy, in the documentation for the Python standard library. It’s useful for knowing what exceptions exist in Python, how the hierarchy looks, and for generally understanding how exceptions work.

But if you look at the bottom of that hierarchy, you’ll see that there’s an exception class called “Warning,” along with a bunch of subclasses such as “DeprecationWarning” and “BytesWarning”. What are these? While they’re included along with the exception hierarchy, warnings are exceptions, but they’re neither raised nor used like normal exceptions. What are they, and how do we use them?

First, some history: Warnings have been around in Python for quite some time, since Python 2.1 (back in the year 2000). PEP 230 was written by Guido van Rossum (the original author of Python and the long-time BDFL), and was added not only to create a mechanism for alerting users to possible problems, but also for sending such alerts from within programs and for deciding what to do with them.

Why warnings?

Before I show you how you can use warnings in your own code, let’s first consider why and when you would want to use warnings. After all, you could always use “print” to display a warning. Or if something is really wrong, then you could raise an exception.

But that’s just the point: There are times when you want to get the user’s attention, but without stopping the program or forcing a try-except clause. And while “print” is often useful, it normally writes to standard output (aka “sys.stdout” in Python), which means that your warnings could get mixed up with the warnings themselves.

(And while I just wrote that you might want to get the user’s attention, I’d argue that most of the time, warnings are aimed at developers rather than users. Warnings in Python are sort of like the “service needed” light on a car; the user might know that something is wrong, but only a qualified repairperson will know what to do. Developers should avoid showing warnings to end users.)

You can also imagine a situation in which some warnings are more important than others. You could certainly devise a scheme in which the program would “print” warnings, and that the warning’s first character would indicate its severity… but why work in this way, when Python has a complete object system, as well as complex data types at its disposal?

Moreover, there are some situations in which a user might not want to dismiss warnings. Maybe I’m running a very sensitive type of program in production, and I’d rather have the program exit prematurely than continue in a potentially ambiguous situation.

Python’s warning system takes all of this into account:

  • It treats the warnings as a separate type of output, so that we cannot confuse it with either exceptions or the program’s printed text,
  • It lets us indicate what kind of warning we’re sending the user,
  • It lets the user indicate what should happen with different types of warnings, with some causing fatal errors, others displaying their messages on the screen, and still others being ignored,
  • It lets programmers develop their own, new kinds of warnings.

Not every program needs to have or use warnings. But your program would like to scold a user for the way that a module was loaded or a function was invoked, then Python’s warnings system provides just what you want.

Warning the user

Let’s say that you want to warn the user about something. You can do so by importing the “warnings” module, and then by using “warnings.warn” to tell them what’s wrong:

import warnings

warnings.warn('I am a warning!')

What happens when I run the above code (in a file I called “warnings1.py”? The following:

./warnings1.py:6: UserWarning: I am a warning!
warnings.warn('I am a warning!')

In other words, the above was all written to my terminal screen. The three lines were all printed in sequence, so it’s not as if the warning was printed at a separate phase (e.g., compilation) of the program. But there is a clear difference between the plain ol’ “print” statements and the output I got from the warning.

First of all, we’re told in which file, and on which line, the warning took place. In a tiny and trivial example like this one, that seems like overkill. But if you have a large application consisting of many different files, then it’ll certainly be nice to know what code generated the warning.

We’re also told that this was a “UserWarning” — one of the types of warnings that we can generate. Just as different types of exceptions allow us to selectively trap them, different types of warnings allow us to handle them differently.

But there’s also something hidden from this output: The “print” statements and my “warnings.warn” statement actually sent their output to two different places. As I wrote above, “print” normally writes to “standard output,” aka “sys.stdout”, typically connected to the user’s terminal window. But “warnings.warn” normally writes to “standard error,” aka “sys.stderr”. The problem is that by default, “sys.stdout” and “sys.stderr” both write to the same place, namely the user’s terminal.

But look at what happens if I redirect program output to a file:

$ ./warnings1.py > output.txt

./warnings1.py:6: UserWarning: I am a warning!
warnings.warn('I am a warning!')

I told my Unix shell that I wanted to run “warnings1.py”, and that all output should be placed in “output.txt”, rather than displayed on the screen. But I didn’t really say “all output.” Rather, by using the “>”, I only redirected output sent to “sys.stdout”. Warnings, which are sent to “sys.stderr”, are still displayed. This is normally considered to be a good thing, ensuring that even if you’ve redirected output to a file, you’ll still be able to see warnings and other errors. So while sys.stdout and sys.stderr both go to the same destination by default, we can see the advantage of being able to separate them.

Different types of warnings

Let’s say that I’m maintaining a library that has been around for some time. The library has a function that works, but which is a bit old-fashioned, and doesn’t support modern use cases. It’s a pain for me, as the library maintainer, to support two versions of the function — the old one and the new one.

I can declare, in documentation and social media, that a new version (3.0) of my library will be out next year, and that this new version won’t support the old version of the function. But we all know that programmers don’t tend to read documentation. So I would prefer to shock users a bit, telling them that while the old function version still works, they should start to move to the newer version.

How can I do that? With warnings, of course! Here’s an example of how that might look:

import warnings

def hello(name):
    warnings.warn('"hello" will be removed in version 3.0')
    return f'Hello, {name}!'

def newhello(name, decoration=''):
    return f'Hello, {decoration}{name}{decoration}!'

print(newhello('world', decoration='*'))

Now, any time a user runs the function “hello”, they’ll get a warning. Moreover, because this warnings goes to standard error (and not standard out), it won’t be mixed with the normal output. Here’s the output from the above:

$ ./warnings2.py

./warnings2.py:7: UserWarning: "hello" will be removed in version 3.0
warnings.warn('"hello" will be removed in version 3.0')
Hello, world!
Hello, *world*!

But it gets better than that: Maybe we want to separate our normal, run-of-the-mill warnings from other types of warnings. For example, we might have a number of functions that are deprecated. To handle this, the “warnings.warn” function supports an optional, second argument — a category of warning. For example, we can use DeprecationWarning:

import warnings

def hello(name):
    warnings.warn('"hello" will be removed in version 3.0',
    return f'Hello, {name}!'

def newhello(name, decoration=''):
    return f'Hello, {decoration}{name}{decoration}!'

print(newhello('world', decoration='*'))

We don’t have to “import” DeprecationWarning, or any other of the standard warning types, because they’re already imported automatically, into the “builtins” namespace that’s always available to a Python program. And indeed, there are a number of such warning classes that we can use, including UserWarning (the default), DeprecationWarning (which we used here), SyntaxWarning, and UnicodeWarning. You can use whichever one of these you deem most appropriate.

You might have noticed that these warning categories are precisely the same classes as we saw earlier, when we were looking through Python’s built-in exception hierarchy. And indeed, this is how those classes are meant to be used, passed as a second argument to “warnings.warn”.

Simple filtering

Let’s say that you are using a bunch of old functions, and that each of those functions are going to warn you that you should really switch to their newer alternatives. You’ll probably get a bit annoyed if every time you run your program, you get a bunch of warnings. The warnings are there to inform you that you should upgrade… but sometimes, the warnings are more annoying than helpful.

In such a case, you might want to filter out some of the warnings. Now, “filtering” is a very general term that’s used by the warnings system. It basically lets you say, “When a warning that matches certain criteria fires, do X with it” — where X can be a variety of things.

The simplest filter is “warnings.simplefilter”, and the simplest way to invoke it is with a single string argument. That argument tells the warning system what to do if it encounters a warning:

  • “default” — display a warning the first time it is encountered
  • “error” — turn the warning into an exception
  • “ignore” — ignore the warning
  • “always” — always show the warning, even if it was displayed before
  • “module” — show the warning once per module
  • “once” — show the warning only once, throughout the program

For example, if I want to ignore all warnings, I could say:


And then if I have code that reads:

warnings.warn('The end is nigh!')

We’ll see output that looks like:


As you can see, the warning disappeared entirely, thanks to the use of “ignore”.

What happens if we take the other extreme, namely we turn the warnings into exceptions?


Sure enough, we then get an exception:

UserWarning: Yikes!

As you can see, we got a UserWarning exception. We can use “try” and “except” on these, trapping them if we want… although I must admit that it seems weird to me to turn warnings into exceptions, only to trap them. (I’m sure that there is a use case for this, though.)

More specific filtering

I mentioned that “simplefilter” takes a mandatory argument, and we’ve seen what those can be. But it turns out that “simplefilter” takes several additional, optional arguments that can be used to specify what happens when a warning is issued.

For example, let’s say I want to ignore UserWarning but turn DeprecationWarning into an exception. I can say:

import warnings

warnings.simplefilter('ignore', UserWarning)
warnings.simplefilter('error', DeprecationWarning)

warnings.warn('bad news!')  # ignored

warnings.warn('very bad news', category=DeprecationWarning)

This code results in the following output:

Traceback (most recent call last):
File "", line 1, in
DeprecationWarning: very bad news

In other words, we successfully ignored one type of warning, while turning another into an exception — which, like all exceptions, is fatal if ignored.

The “simplefilter” function takes four arguments, all but the first being optional

What else can you do?

The warning system handles a very wide variety of cases, and can be configured in numerous ways. Among other things, you can:

  • Define warning filters from the command line, using the -W flag
  • Set multiple filters, each handling a different case
  • Specify the message and module that should be filtered, either as a string or as a regular expression
  • Create your own warnings, as subclasses of existing warning classes
  • Capture warnings with Python’s logging module, rather than printing the output to sys.stderr.
  • Have output go to a callable (i.e., function or class) of your choice, rather than to sys.stderr, for fancier processing.

Interested in learning more?

Related Posts

Prepare yourself for a better career, with my new Python learning memberships

Prepare yourself for a better career, with my new Python learning memberships

I’m banned for life from advertising on Meta. Because I teach Python.

I’m banned for life from advertising on Meta. Because I teach Python.

Sharpen your Pandas skills with “Bamboo Weekly”

Sharpen your Pandas skills with “Bamboo Weekly”
  • 👏 good read. I used to avoid using warnings because i thought they were overkill. Now i see their essence…

  • {"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}