{"record":{"id":"67cb73c86e94a03d","repo":"pandas-dev/pandas","slug":"expression-objects-are-not-copiable","errorCode":null,"errorMessage":"Expression objects are not copiable","messagePattern":"Expression objects are not copiable","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"pandas/core/col.py","lineNumber":363,"sourceCode":"                evaluated.append((condition, replacement))\n            return ser.case_when(evaluated)\n\n        # Keep repr compact; caselist may be large.\n        repr_str = f\"{self!r}.case_when(...)\"\n        return Expression(func, repr_str)\n\n    def __repr__(self) -> str:\n        return self._repr_str or \"Expr(...)\"\n\n    # Unsupported ops\n    def __bool__(self) -> NoReturn:\n        raise TypeError(\"boolean value of an expression is ambiguous\")\n\n    def __iter__(self) -> NoReturn:\n        raise TypeError(\"Expression objects are not iterable\")\n\n    def __copy__(self) -> NoReturn:\n        raise TypeError(\"Expression objects are not copiable\")\n\n    def __deepcopy__(self, memo: dict[int, Any] | None) -> NoReturn:\n        raise TypeError(\"Expression objects are not copiable\")\n\n\n@set_module(\"pandas\")\ndef col(col_name: Hashable) -> Expression:\n    \"\"\"\n    Generate deferred object representing a column of a DataFrame.\n\n    Any place which accepts ``lambda df: df[col_name]``, such as\n    :meth:`DataFrame.assign` or :meth:`DataFrame.loc`, can also accept\n    ``pd.col(col_name)``.\n\n    .. versionadded:: 3.0.0\n\n    Parameters\n    ----------","sourceCodeStart":345,"sourceCodeEnd":381,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/col.py#L345-L381","documentation":"Raised by Expression.__copy__ (typed NoReturn) when copy.copy() is called on a pandas.api.typing.Expression. Expression objects intentionally forbid shallow copies to preserve their identity as deferred singletons bound to a specific closure; copying them could break the func->DataFrame evaluation chain. The same message is reused for both __copy__ and __deepcopy__.","triggerScenarios":"copy.copy(pd.col('a')); a library that auto-copies its inputs (e.g. functools.partial dispatch, some ORM wrappers); pickle/copy protocols that fall back to __copy__.","commonSituations":"Calling copy.copy on a heterogeneous collection that happens to contain an Expression; framework code that defensively copies user-supplied callables.","solutions":["Do not copy Expression objects; treat them as opaque singletons.","Filter Expression out before copying: skip objects whose type name is 'Expression'.","Re-create the Expression from its source via pd.col(name) if you need a logically equivalent one."],"exampleFix":"// before\nexpr2 = copy.copy(pd.col('a'))\n// after\nexpr2 = pd.col('a')  # same singleton, or rebuild from name","handlingStrategy":"type-guard","validationCode":"from pandas.api.typing import Expression\nif isinstance(obj, Expression):\n    raise TypeError('do not copy.copy() an Expression')","typeGuard":"def is_expression(x) -> bool:\n    from pandas.api.typing import Expression\n    return isinstance(x, Expression)","tryCatchPattern":null,"preventionTips":["Treat Expression as an opaque singleton; never copy it.","Filter Expression out before bulk copy.copy on collections."],"tags":["type-error","expression","col","copy","deferred"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}