python/cpython · error · TypeError

module must be a string

Error message

module must be a string

What it means

Raised by warnings.filterwarnings when the module argument is not a str. Like message, module is a regex pattern string that the function compiles internally (re.compile(module)); pre-compiled patterns, bytes, or None passed positionally are rejected with TypeError('module must be a string').

Source

Thrown at Lib/_py_warnings.py:273

                   append=False):
    """Insert an entry into the list of warnings filters (at the front).

    'action' -- one of "error", "ignore", "always", "all", "default", "module",
                or "once"
    'message' -- a regex that the warning message must match
    'category' -- a class that the warning must be a subclass of
    'module' -- a regex that the module name must match
    'lineno' -- an integer line number, 0 matches all warnings
    'append' -- if true, append to the list of filters
    """
    if action not in {"error", "ignore", "always", "all", "default", "module", "once"}:
        raise ValueError(f"invalid action: {action!r}")
    if not isinstance(message, str):
        raise TypeError("message must be a string")
    if not isinstance(category, type) or not issubclass(category, Warning):
        raise TypeError("category must be a Warning subclass")
    if not isinstance(module, str):
        raise TypeError("module must be a string")
    if not isinstance(lineno, int):
        raise TypeError("lineno must be an int")
    if lineno < 0:
        raise ValueError("lineno must be an int >= 0")

    if message or module:
        import re

    if message:
        message = re.compile(message, re.I)
    else:
        message = None
    if module:
        module = re.compile(module)
    else:
        module = None

    _wm._add_filter(action, message, category, module, lineno, append=append)

View on GitHub (pinned to bc6749cc3b)

Solutions

  1. Pass the pattern as a str: module=r'^mymod\..*'
  2. Unwrap compiled patterns: getattr(module, 'pattern', module)
  3. For 'all modules' use the default empty string, not None

Example fix

# before
warnings.filterwarnings('ignore', module=re.compile('mylib'))  # TypeError

# after
warnings.filterwarnings('ignore', module=r'mylib')
Defensive patterns

Strategy: validation

Validate before calling

def to_pattern_str(mod):
    return getattr(mod, 'pattern', mod)

import warnings
warnings.filterwarnings('ignore', module=to_pattern_str(user_module))

Type guard

def is_pattern_str(mod) -> bool:
    return isinstance(mod, str)

Prevention

When it happens

Trigger: warnings.filterwarnings('ignore', module=re.compile('mymod')); module=b'mymod'; module=None passed explicitly; module/class arguments swapped in positional calls.

Common situations: Pre-compiled regex reuse; kwargs/positional mix-ups in long filterwarnings calls; programmatically assembled filter entries where a compiled pattern object leaks in; bytes literals copied from network-layer code.

Related errors


AI-assisted analysis of python/cpython@bc6749cc3b (2026-08-14). Data as JSON: /api/errors/1da3458e192de851. Report an issue: GitHub.