{"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":2911,"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":2893,"sourceCodeEnd":2929,"githubUrl":"https://github.com/pola-rs/polars/blob/df599052daf96e7a9cc30a3b0c6bd25d6947e3c0/py-polars/src/polars/expr/string.py#L2893-L2929","documentation":"Expr.str.replace_many accepts patterns without replace_with only when patterns is a Mapping (dict of pattern to replacement); keys and values are then split internally. With a list, Series, or Expr of patterns the replacements are unknown, so omitting replace_with raises a TypeError immediately.","triggerScenarios":".str.replace_many(['foo', 'bar']) with no second argument; passing a Series of patterns positionally; refactoring a dict into two parallel lists and forgetting to add replace_with; wrapper functions that forward patterns but drop the default replace_with.","commonSituations":"Token replacement tables loaded from CSV/DB as two parallel columns; building patterns dynamically at runtime; migrating from chained .str.replace calls where the replacement was always given.","solutions":["Pass a dict: .str.replace_many({'foo': 'bar', 'a': 'b'})","Or keep the list and provide replace_with: .str.replace_many(pats, replace_with=repls) — a scalar or list-like of replacements","If patterns/replacements come from a frame, pass expressions: .str.replace_many(pl.col('pats'), replace_with=pl.col('repls'))"],"exampleFix":"# before\npl.col('s').str.replace_many(['foo', 'bar'])\n\n# after (mapping)\npl.col('s').str.replace_many({'foo': 'bar', 'bar': 'baz'})\n\n# after (parallel lists)\npl.col('s').str.replace_many(pats, replace_with=repls)","handlingStrategy":"validation","validationCode":"from collections.abc import Mapping\nif not isinstance(patterns, Mapping) and replace_with is None:\n    raise ValueError('replace_with is required for non-mapping patterns')\nexpr = pl.col('s').str.replace_many(patterns, replace_with=replace_with)","typeGuard":"from collections.abc import Mapping\n\ndef is_pattern_mapping(x: object) -> bool:\n    return isinstance(x, Mapping)","tryCatchPattern":null,"preventionTips":["Prefer the dict form (patterns -> replacements) as the default","When loading replacement tables from files, build a dict immediately","Wrap the API in one helper that always supplies replace_with for lists"],"tags":["polars","string","typeerror","replace","mapping"],"backgroundTag":null,"analyzedSha":"df599052daf96e7a9cc30a3b0c6bd25d6947e3c0","analyzedAt":"2026-08-16T12:10:03.978Z","schemaVersion":2},"datasetVersion":"2026-08-16T13:17:31.715Z"}