{"record":{"id":"dc42326b4374dbbf","repo":"pandas-dev/pandas","slug":"you-cannot-add-any-new-attribute-key","errorCode":null,"errorMessage":"You cannot add any new attribute '{key}'","messagePattern":"You cannot add any new attribute '(.+?)'","errorType":"exception","errorClass":"AttributeError","httpStatus":null,"severity":"error","filePath":"pandas/core/base.py","lineNumber":161,"sourceCode":"    def _freeze(self) -> None:\n        \"\"\"\n        Prevents setting additional attributes.\n        \"\"\"\n        object.__setattr__(self, \"__frozen\", True)\n\n    # prevent adding any attribute via s.xxx.new_attribute = ...\n    def __setattr__(self, key: str, value) -> None:\n        # _cache is used by a decorator\n        # We need to check both 1.) cls.__dict__ and 2.) getattr(self, key)\n        # because\n        # 1.) getattr is false for attributes that raise errors\n        # 2.) cls.__dict__ doesn't traverse into base classes\n        if getattr(self, \"__frozen\", False) and not (\n            key == \"_cache\"\n            or key in type(self).__dict__\n            or getattr(self, key, None) is not None\n        ):\n            raise AttributeError(f\"You cannot add any new attribute '{key}'\")\n        object.__setattr__(self, key, value)\n\n\nclass SelectionMixin(Generic[NDFrameT]):\n    \"\"\"\n    mixin implementing the selection & aggregation interface on a group-like\n    object sub-classes need to define: obj, exclusions\n    \"\"\"\n\n    obj: NDFrameT\n    _selection: IndexLabel | None = None\n    exclusions: frozenset[Hashable]\n    _internal_names = [\"_cache\", \"__setstate__\"]\n    _internal_names_set = set(_internal_names)\n\n    @final\n    @property\n    def _selection_list(self):","sourceCodeStart":143,"sourceCodeEnd":179,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/base.py#L143-L179","documentation":"Raised by PandasObject.__setattr__ on instances that have been frozen via _freeze() (which sets the private __frozen flag). Once frozen, only attributes that are '_cache', already declared on the class (in type(self).__dict__), or already present on the instance may be set; any brand-new attribute raises AttributeError. This prevents accidental monkey-patching of results/immutable objects.","triggerScenarios":"Setting a custom attribute on a frozen instance, e.g. `frozen_series.my_attr = 1`, where the instance had `_freeze()` called (common on certain Index/manager internals or frozen views).","commonSituations":"Attempting to attach metadata to a returned/frozen object; library-internal freeze applied to objects the user expected to be mutable.","solutions":["Store the metadata in a separate dict/data structure keyed by the object, rather than as an attribute on it.","If the object is your own subclass, declare the attribute on the class so __setattr__ permits it.","Avoid relying on attribute attachment for frozen/immutable pandas results."],"exampleFix":"# before\ns.my_custom_field = 42  # AttributeError when s is frozen\n\n# after\nmeta = {id(s): 42}  # keep metadata out-of-band","handlingStrategy":"type-guard","validationCode":"def can_set_attr(obj, key: str) -> bool:\n    if not getattr(obj, '__frozen', False):\n        return True\n    return key == '_cache' or key in type(obj).__dict__ or getattr(obj, key, None) is not None","typeGuard":"def is_frozen(obj) -> bool:\n    return bool(getattr(obj, '__frozen', False))","tryCatchPattern":"try:\n    obj.my_attr = value\nexcept AttributeError as e:\n    if 'cannot add any new attribute' in str(e):\n        metadata[id(obj)] = value  # store out-of-band\n    else:\n        raise","preventionTips":["Do not attach custom attributes to pandas result objects; use a side dict keyed by identity.","For subclasses, declare attributes on the class so __setattr__ permits them.","Check the __frozen flag before attempting attribute assignment."],"tags":["base","attribute","frozen","attributeerror","immutable"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}