WarningPython Error

UserWarning

UserWarning: this is a custom warning

Traceback

terminal
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    warnings.warn("config file not found, using defaults")
UserWarning: this is a custom warning

What causes this error

User code or a library issued a warning via the warnings module. This is the default warning category for general-purpose notifications.

How to fix it

Read the warning message and address the underlying issue. Use `warnings.filterwarnings()` to suppress known harmless warnings. For your own code, use specific warning subclasses instead of generic UserWarning.

Code that causes this error

Broken
import warnings
warnings.warn("config file not found, using defaults")

Fixed code

Fixed
import warnings

class ConfigWarning(UserWarning):
    pass

if not config_exists:
    warnings.warn(
        "config file not found, using defaults",
        ConfigWarning,
        stacklevel=2,
    )

About UserWarning

UserWarning is the default category for warnings issued by user code via `warnings.warn()`. It is the base class used when no specific warning category is provided. Libraries and applications use UserWarning for non-critical notifications about potential issues: deprecated usage patterns, suboptimal configurations, missing optional dependencies, and performance concerns.

Unlike more specific warning categories (DeprecationWarning, FutureWarning), UserWarning is always shown by default. To issue a custom warning, call `warnings.warn('message')` or `warnings.warn('message', UserWarning)`. For better categorization, create custom warning subclasses: `class MyLibraryWarning(UserWarning): pass`.

The `warnings` module provides `filterwarnings()` to control which warnings are shown, turned into errors, or suppressed.

Common scenarios

1

Using deprecated APIs that will be removed in future versions

2

Performing numerical operations that produce inf or NaN values

3

Leaving files, sockets, or connections open without proper cleanup

4

Calling async functions without awaiting the result

Related errors