pytest-dev/pytest · error · UsageError

is not a Warning subclass

Error message

{cat} is not a Warning subclass

What it means

Raised by _resolve_warning_category() when the category name in a warning filter resolves to a class that is not a subclass of Warning. Warning filters require the category field to be a Warning subclass (e.g., DeprecationWarning, UserWarning). The resolved class is checked with issubclass(cat, Warning).

Solutions

  1. Use a Warning subclass: DeprecationWarning, UserWarning, RuntimeWarning, FutureWarning, etc.
  2. For custom warnings, ensure the class inherits from Warning (or a Warning subclass)
  3. Use the bare 'Warning' category (empty field defaults to Warning) to match all warnings

Example fix

# before
filterwarnings = ["ignore::ValueError"]

# after
filterwarnings = ["ignore::UserWarning"]
Defensive patterns

Strategy: validation

Validate before calling

import importlib
from warnings import Warning
def validate_warning_category(category: str) -> bool:
    if not category:
        return True  # defaults to Warning
    if '.' not in category:
        import builtins
        cat = getattr(builtins, category, None)
    else:
        module, _, klass = category.rpartition('.')
        try:
            m = importlib.import_module(module)
            cat = getattr(m, klass, None)
        except ImportError:
            return False
    return cat is not None and isinstance(cat, type) and issubclass(cat, Warning)

Type guard

from warnings import Warning
def is_warning_subclass(cls: type) -> bool:
    return isinstance(cls, type) and issubclass(cls, Warning)

Try / catch

from pytest import UsageError
try:
    parse_warning_filter(arg, escape=True)
except UsageError as e:
    print(f"Invalid warning category: {e}")

Prevention

When it happens

Trigger: Providing a warning filter where the category field names a class that is not a Warning subclass. Example: filterwarnings = ["ignore::ValueError"] or ["ignore::os.PathLike"]. The category is resolved via importlib/import and getattr, then the issubclass check fails.

Common situations: Using a built-in exception class (e.g., ValueError, RuntimeError) instead of a Warning subclass. Typo in the category name resolving to a non-Warning class. Specifying a fully-qualified path to a custom class that does not inherit from Warning.

Related errors


AI-assisted analysis of pytest-dev/pytest@0d6fbdeffa (2026-08-11). Data as JSON: /api/errors/fc099e9a229a78aa. Report an issue: GitHub.

Appendix: source

Thrown at src/_pytest/config/__init__.py:2344

def _resolve_warning_category(category: str) -> type[Warning]:
    """
    Copied from warnings._getcategory, but changed so it lets exceptions (specially ImportErrors)
    propagate so we can get access to their tracebacks (#9218).
    """
    __tracebackhide__ = True
    if not category:
        return Warning

    if "." not in category:
        import builtins as m

        klass = category
    else:
        module, _, klass = category.rpartition(".")
        m = importlib.import_module(module)
    cat = getattr(m, klass)
    if not issubclass(cat, Warning):
        raise UsageError(f"{cat} is not a Warning subclass")
    return cast(type[Warning], cat)


def apply_warning_filters(
    config_filters: Iterable[str], cmdline_filters: Iterable[str]
) -> None:
    """Applies pytest-configured filters to the warnings module"""
    # Filters should have this precedence: cmdline options, config.
    # Filters should be applied in the inverse order of precedence.
    for arg in config_filters:
        try:
            warnings.filterwarnings(*parse_warning_filter(arg, escape=False))
        except ImportError as e:
            warnings.warn(
                f"Failed to import filter module '{e.name}': {arg}", PytestConfigWarning
            )
            continue

View on GitHub (pinned to 0d6fbdeffa)