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
- Coerce the input with str(value) before calling
- Handle None/missing values before calling escape_regex
- For multiple strings, loop or use the expression API on a Series/DataFrame column
- 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
- Validate user-supplied patterns are str before use
- Decode bytes with explicit encoding before regex escaping
- Coalesce None/missing values to a default string or skip early
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
- "extract_groups" expects a `str`, given a
- arr.to_struct() got a str instead of a list. hint: pass
- Array constructor is missing the required argument `shape`
- cannot call `map_groups` when filtering groups with `having`
- cannot call `map_groups` when grouping by an expression
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)