pola-rs/polars · error · TypeError

escape_regex function supports only `str` type, got

Error message

escape_regex function supports only `str` type, got `{qualified_type_name(s)}`

What it means

Type guard in the top-level escape_regex function: it accepts only a plain str input. An Expr input gets a dedicated hint to use Expr.str.escape_regex instead, and any other non-str type raises this generic TypeError.

Solutions

  1. Coerce the input with str(value) before calling
  2. Handle None/missing values before calling escape_regex
  3. For multiple strings, loop or use the expression API on a Series/DataFrame column
  4. Add an isinstance(value, str) guard in calling code

Example fix

// before
escaped = pl.escape_regex(user_input)  # may be None
// after
escaped = pl.escape_regex(user_input) if isinstance(user_input, str) else None
Defensive patterns

Strategy: type-guard

Validate before calling

if not isinstance(pattern, str):
    raise TypeError(f'expected str for escape_regex, got {type(pattern).__name__}')

Type guard

def is_str_or_none(x) -> bool:
    return x is None or isinstance(x, str)

Try / catch

try:
    escaped = pl.escape_regex(pattern)
except TypeError as e:
    logger.warning('escape_regex got non-str: %s', e)
    escaped = None

Prevention

When it happens

Trigger: pl.escape_regex(123), pl.escape_regex(b'pattern'), pl.escape_regex(None), or passing a list of strings instead of a single string.

Common situations: A variable expected to hold a string is None due to a failed lookup; passing bytes read from a file; forgetting that the function is not vectorized over collections.

Understand the failure class

Background: Type mismatch errors: IllegalArgumentException, TypeError and type guards across 150 open-source libraries — this error's family across 150 libraries.

Related errors


AI-assisted analysis of pola-rs/polars@fe841f959e (2026-09-18). Data as JSON: /api/errors/90d475d98bf5c5be. Report an issue: GitHub.

Appendix: source

Thrown at py-polars/src/polars/functions/escape_regex.py:27

import polars._reexport as pl


def escape_regex(s: str) -> str:
    r"""
    Escapes string regex meta characters.

    Parameters
    ----------
    s
        The string whose meta characters will be escaped.

    """
    if isinstance(s, pl.Expr):
        msg = "escape_regex function is unsupported for `Expr`, you may want use `Expr.str.escape_regex` instead"
        raise TypeError(msg)
    elif not isinstance(s, str):
        msg = f"escape_regex function supports only `str` type, got `{qualified_type_name(s)}`"
        raise TypeError(msg)

    return plr.escape_regex(s)

View on GitHub (pinned to fe841f959e)