pola-rs/polars · error · TypeError

`replace_with` argument is required if `patterns` argument…

Error message

`replace_with` argument is required if `patterns` argument is not a Mapping type

What it means

Expr.str.replace_many() replaces many patterns at once; the replacements must come either from a Mapping (patterns->replacements) or from an explicit `replace_with` argument. If `patterns` is a plain list and `replace_with` was not supplied, polars cannot know the replacements and raises TypeError.

Solutions

  1. Pass `replace_with` as a list parallel to `patterns`
  2. Or pass a single Mapping as `patterns`, e.g. `{'a':'z','b':'y'}`
  3. Or supply a default value via `default` if you intended mapping-style use

Example fix

// before
pl.col('x').str.replace_many(['cat', 'dog'])
// after
pl.col('x').str.replace_many(['cat', 'dog'], ['kitten', 'puppy'])
Defensive patterns

Strategy: validation

Validate before calling

if not isinstance(patterns, Mapping) and replace_with is NO_DEFAULT:
    raise ValueError('provide replace_with list or a Mapping for patterns')

Type guard

def is_mapping(p) -> TypeGuard[Mapping]:
    return isinstance(p, Mapping)

Try / catch

try:
    expr = pl.col('x').str.replace_many(patterns, replace_with)
except TypeError:
    expr = pl.col('x').str.replace_many(dict(zip(patterns, replacements)))

Prevention

When it happens

Trigger: Calling `pl.col('x').str.replace_many(['a','b'])` without `replace_with`, and `patterns` is not a dict.

Common situations: Refactoring code from a list-of-patterns call and forgetting the parallel replacements list; confusing replace_many with str.replace_many dict-style usage.

Understand the failure class

Background: "missing required argument" and "the following required arguments were not provided": what required-argument errors mean and how to fix them — this error's family across 20 libraries.

Related errors


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

Appendix: source

Thrown at py-polars/src/polars/expr/string.py:2860

        >>> df = pl.DataFrame({"haystack": ["abcd"]})
        >>> patterns = {"abcd": "z", "abc": "y", "b": "x"}
        >>> df.with_columns(
        ...     replaced=pl.col("haystack").str.replace_many(patterns, leftmost=True)
        ... )
        shape: (1, 2)
        ┌──────────┬──────────┐
        │ haystack ┆ replaced │
        │ ---      ┆ ---      │
        │ str      ┆ str      │
        ╞══════════╪══════════╡
        │ abcd     ┆ z        │
        └──────────┴──────────┘
        """  # noqa: W505
        if replace_with is NO_DEFAULT:
            if not isinstance(patterns, Mapping):
                msg = "`replace_with` argument is required if `patterns` argument is not a Mapping type"
                raise TypeError(msg)
            # Early return in case of an empty mapping.
            if not patterns:
                return wrap_expr(self._pyexpr)
            replace_with = list(patterns.values())
            patterns = list(patterns.keys())

        patterns_pyexpr = parse_into_expression(
            patterns,  # type: ignore[arg-type]
            str_as_lit=False,
        )
        replace_with_pyexpr = parse_into_expression(replace_with, str_as_lit=True)
        return wrap_expr(
            self._pyexpr.str_replace_many(
                patterns_pyexpr, replace_with_pyexpr, ascii_case_insensitive, leftmost
            )
        )

    @unstable()

View on GitHub (pinned to fe841f959e)