{"record":{"id":"5f5b0332663e9da6","repo":"pola-rs/polars","slug":"replace-with-argument-is-required-if-patterns","errorCode":null,"errorMessage":"`replace_with` argument is required if `patterns` argument is not a Mapping type","messagePattern":"`replace_with` argument is required if `patterns` argument is not a Mapping type","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/expr/string.py","lineNumber":2860,"sourceCode":"\n        >>> df = pl.DataFrame({\"haystack\": [\"abcd\"]})\n        >>> patterns = {\"abcd\": \"z\", \"abc\": \"y\", \"b\": \"x\"}\n        >>> df.with_columns(\n        ...     replaced=pl.col(\"haystack\").str.replace_many(patterns, leftmost=True)\n        ... )\n        shape: (1, 2)\n        ┌──────────┬──────────┐\n        │ haystack ┆ replaced │\n        │ ---      ┆ ---      │\n        │ str      ┆ str      │\n        ╞══════════╪══════════╡\n        │ abcd     ┆ z        │\n        └──────────┴──────────┘\n        \"\"\"  # noqa: W505\n        if replace_with is NO_DEFAULT:\n            if not isinstance(patterns, Mapping):\n                msg = \"`replace_with` argument is required if `patterns` argument is not a Mapping type\"\n                raise TypeError(msg)\n            # Early return in case of an empty mapping.\n            if not patterns:\n                return wrap_expr(self._pyexpr)\n            replace_with = list(patterns.values())\n            patterns = list(patterns.keys())\n\n        patterns_pyexpr = parse_into_expression(\n            patterns,  # type: ignore[arg-type]\n            str_as_lit=False,\n        )\n        replace_with_pyexpr = parse_into_expression(replace_with, str_as_lit=True)\n        return wrap_expr(\n            self._pyexpr.str_replace_many(\n                patterns_pyexpr, replace_with_pyexpr, ascii_case_insensitive, leftmost\n            )\n        )\n\n    @unstable()","sourceCodeStart":2842,"sourceCodeEnd":2878,"githubUrl":"https://github.com/pola-rs/polars/blob/fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e/py-polars/src/polars/expr/string.py#L2842-L2878","documentation":"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.","triggerScenarios":"Calling `pl.col('x').str.replace_many(['a','b'])` without `replace_with`, and `patterns` is not a dict.","commonSituations":"Refactoring code from a list-of-patterns call and forgetting the parallel replacements list; confusing replace_many with str.replace_many dict-style usage.","solutions":["Pass `replace_with` as a list parallel to `patterns`","Or pass a single Mapping as `patterns`, e.g. `{'a':'z','b':'y'}`","Or supply a default value via `default` if you intended mapping-style use"],"exampleFix":"// before\npl.col('x').str.replace_many(['cat', 'dog'])\n// after\npl.col('x').str.replace_many(['cat', 'dog'], ['kitten', 'puppy'])","handlingStrategy":"validation","validationCode":"if not isinstance(patterns, Mapping) and replace_with is NO_DEFAULT:\n    raise ValueError('provide replace_with list or a Mapping for patterns')","typeGuard":"def is_mapping(p) -> TypeGuard[Mapping]:\n    return isinstance(p, Mapping)","tryCatchPattern":"try:\n    expr = pl.col('x').str.replace_many(patterns, replace_with)\nexcept TypeError:\n    expr = pl.col('x').str.replace_many(dict(zip(patterns, replacements)))","preventionTips":["Prefer the Mapping form `{'cat':'kitten'}` which is self-describing","Keep patterns and replacements lists the same length via zip assertions in tests"],"tags":["polars","type-error","missing-argument","python"],"backgroundTag":"missing-required-argument","analyzedSha":"fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e","analyzedAt":"2026-09-18T22:14:11.667Z","contentChangedAt":"2026-09-18T22:14:11.667Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}