{"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/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/computation/eval.py#L407-L443","documentation":"When inplace=False and there is an assignment, eval.py:417 copies the target on the first assignment so the original object is untouched. For NDFrame it uses copy(deep=False); for anything else it calls target.copy(). If the target object has no copy method, AttributeError is caught at eval.py:424 and re-raised as this ValueError naming the conceptual problem (cannot return a copy).","triggerScenarios":"pd.eval('a = 1', target=some_object, inplace=False) where some_object lacks a .copy() method — e.g. a custom dict subclass, a list, or a third-party container.","commonSituations":"Plugging a custom namespace object as target. Using a plain dict-like that doesn't implement copy. Testing eval with a mock target.","solutions":["Set inplace=True to skip the copy path entirely.","Pass an NDFrame (DataFrame/Series) target, which has a working copy(deep=False).","Add a .copy() method to your custom target class that returns a shallow copy."],"exampleFix":"// before\npd.eval('a = 1', target=my_obj, inplace=False)\n// after\npd.eval('a = 1', target=my_obj, inplace=True)","handlingStrategy":"validation","validationCode":"def validate_target_supports_copy(target) -> None:\n    if not hasattr(target, 'copy'):\n        raise ValueError(\n            f'target {type(target).__name__} has no .copy(); '\n            'use inplace=True or an NDFrame/dict target'\n        )\n\n# only when inplace=False and an assignment is present:\nif not inplace and has_assignment:\n    validate_target_supports_copy(target)","typeGuard":"def target_can_copy(target) -> bool:\n    return hasattr(target, 'copy') and callable(getattr(target, 'copy'))","tryCatchPattern":"try:\n    pd.eval(expr, target=target, inplace=False)\nexcept ValueError as e:\n    if 'copy of the target' in str(e):\n        pd.eval(expr, target=target, inplace=True)  # mutate instead\n    else:\n        raise","preventionTips":["Prefer DataFrame/dict targets which support copy.","Use inplace=True for custom targets that lack copy.","Add a .copy() method to custom namespace objects used as eval targets."],"tags":["pandas","eval","target","inplace","copy"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}