{"record":{"id":"709c7baff902ec36","repo":"pandas-dev/pandas","slug":"cannot-return-a-copy-of-the-target","errorCode":null,"errorMessage":"Cannot return a copy of the target","messagePattern":"Cannot return a copy of the target","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/computation/eval.py","lineNumber":425,"sourceCode":"                )\n            if inplace:\n                raise ValueError(\"Cannot operate inplace if there is no assignment\")\n\n        # assign if needed\n        assigner = parsed_expr.assigner\n        if env.target is not None and assigner is not None:\n            target_modified = True\n\n            # if returning a copy, copy only on the first assignment\n            if not inplace and first_expr:\n                try:\n                    target = env.target\n                    if isinstance(target, NDFrame):\n                        target = target.copy(deep=False)\n                    else:\n                        target = target.copy()\n                except AttributeError as err:\n                    raise ValueError(\"Cannot return a copy of the target\") from err\n            else:\n                target = env.target\n\n            # TypeError is most commonly raised (e.g. int, list), but you\n            # get IndexError if you try to do this assignment on np.ndarray.\n            # we will ignore numpy warnings here; e.g. if trying\n            # to use a non-numeric indexer\n            try:\n                if inplace and isinstance(target, NDFrame):\n                    target.loc[:, assigner] = ret\n                else:\n                    target[assigner] = ret  # pyright: ignore[reportIndexIssue]\n            except (TypeError, IndexError) as err:\n                raise ValueError(\"Cannot assign expression output to target\") from err\n\n            if not resolvers:\n                resolvers = ({assigner: ret},)\n            else:","sourceCodeStart":407,"sourceCodeEnd":443,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/computation/eval.py#L407-L443","documentation":"Raised when inplace=False, an assignment exists, and the target object does not support .copy(). When returning a copy (the default for inplace=False), pandas calls target.copy() (or target.copy(deep=False) for NDFrame) so the original is not mutated. If the target is a type without a .copy() method (e.g., an int, a plain list used as a target, or a custom object), the AttributeError is caught and re-raised as this ValueError.","triggerScenarios":"Calling pd.eval('x = 1', target=5, inplace=False) where target is an int — ints have no .copy(). Or target=some_list where list.copy exists but a different non-copyable object was passed.","commonSituations":"Using a plain Python object (int, tuple, or a namespace object) as a target for pd.eval assignment instead of a DataFrame, dict, or other copyable container; experimentation with target types.","solutions":["Use a DataFrame or dict as the target: pd.eval('x = 1', target={}) or target=df.","Pass inplace=True to avoid the copy step — but only if you intend to mutate the original target in place.","Wrap your target in a type that supports .copy() (e.g., a dict or a custom class with a copy method)."],"exampleFix":"// before\npd.eval('x = 1', target=5)\n\n// after\ntarget = {}\npd.eval('x = 1', target=target)  # returns {'x': 1}","handlingStrategy":"type-guard","validationCode":"if target is not None and not hasattr(target, 'copy'):\n    raise TypeError(f'target {type(target).__name__} must support .copy() when inplace=False')\npd.eval(expr, target=target, inplace=False)","typeGuard":"def is_copyable_target(t) -> bool:\n    return t is None or hasattr(t, 'copy')","tryCatchPattern":"try:\n    pd.eval(expr, target=target)\nexcept ValueError as e:\n    if 'Cannot return a copy' in str(e):\n        result = pd.eval(expr, target=target, inplace=True)\n    else:\n        raise","preventionTips":["Use DataFrame or dict as target.","Avoid passing scalars or immutable types as target.","Validate target supports .copy() for inplace=False."],"tags":["pandas","eval","target","copy","assignment"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}