Python
warnings
exception handling
programming tips
software development

Raise warning in Python without interrupting program

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

If you want to notify the caller about a risky or deprecated situation without stopping execution, use Python’s warnings module. A warning is different from an exception: it communicates that something is undesirable or noteworthy, but normal control flow can continue.

The Standard Tool: warnings.warn

The core API is warnings.warn().

python
1import warnings
2
3
4def divide(a, b):
5    if b == 0:
6        warnings.warn("b is zero; returning None", RuntimeWarning)
7        return None
8    return a / b
9
10
11print(divide(10, 0))
12print("program continues")

This emits a warning and keeps running.

Choose the Warning Category Intentionally

Python warning categories help callers filter different kinds of warnings. Common choices include:

  • 'UserWarning for general application-level warnings'
  • 'DeprecationWarning for deprecated APIs'
  • 'RuntimeWarning for suspicious runtime conditions'
  • 'FutureWarning for behavior that will change later'

Example:

python
import warnings

warnings.warn("old_api() is deprecated", DeprecationWarning)

Using the right category makes the warning much more useful to downstream users and test suites.

Create Custom Warning Types

For libraries, a custom warning class is often cleaner than reusing a generic category.

python
1import warnings
2
3class ConfigurationWarning(UserWarning):
4    pass
5
6
7def load_config(path):
8    if path.endswith(".bak"):
9        warnings.warn("using a backup config file", ConfigurationWarning)

Now consumers can filter that warning precisely.

Warning Behavior Can Be Configured

Warnings do not always display the same way. Python lets you control them with filters.

Example:

python
import warnings

warnings.simplefilter("always", UserWarning)

Common actions include:

  • 'ignore'
  • 'default'
  • 'always'
  • 'once'
  • 'error'

This matters because a warning you raise may be hidden, shown once, or even converted into an exception depending on runtime settings.

Warnings in Tests

Warnings are especially useful in library development because tests can choose to fail on them without changing production behavior.

For example, a test suite may do:

python
import warnings

warnings.simplefilter("error", DeprecationWarning)

That turns deprecation warnings into hard failures during CI, while normal users still see them as warnings.

When to Use a Warning Instead of an Exception

Use a warning when:

  • the program can continue safely
  • the behavior is allowed but discouraged
  • you want to signal future breakage or deprecation
  • the caller may want to handle the situation later

Use an exception when the operation cannot proceed correctly or safely.

That distinction is important. Warnings are communication, not error recovery.

A plain print() statement is not a warning system. It cannot be filtered, categorized, or promoted to an error by callers. For reusable code, warnings.warn() is much more appropriate than printing to standard output.

That also means warning-based APIs integrate better with test runners, CI policy, and downstream library consumers who want centralized control over what gets ignored, shown once, or escalated.

Common Pitfalls

The biggest mistake is using warnings for conditions that should really be exceptions. If the function cannot return a valid result, do not hide the failure behind a warning.

Another issue is choosing the wrong warning category. A vague UserWarning works, but it is less helpful than a well-chosen built-in or custom type.

Developers also sometimes expect warnings to appear every time. Filters may suppress repeated warnings unless configured otherwise.

Finally, do not replace normal logging with warnings. Logging and warnings serve different purposes.

Summary

  • Use warnings.warn() to notify without interrupting execution.
  • Pick a warning category that matches the situation.
  • Create custom warning classes for reusable libraries when needed.
  • Warning behavior can be filtered or even turned into exceptions.
  • Use warnings for recoverable concerns, not for unrecoverable errors.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.