pandas-dev/pandas · error · AttributeError

You cannot add any new attribute

Error message

You cannot add any new attribute '{key}'

What it means

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.

Solutions

  1. Store the metadata in a separate dict/data structure keyed by the object, rather than as an attribute on it.
  2. If the object is your own subclass, declare the attribute on the class so __setattr__ permits it.
  3. Avoid relying on attribute attachment for frozen/immutable pandas results.

Example fix

# before
s.my_custom_field = 42  # AttributeError when s is frozen

# after
meta = {id(s): 42}  # keep metadata out-of-band
Defensive patterns

Strategy: type-guard

Validate before calling

def can_set_attr(obj, key: str) -> bool:
    if not getattr(obj, '__frozen', False):
        return True
    return key == '_cache' or key in type(obj).__dict__ or getattr(obj, key, None) is not None

Type guard

def is_frozen(obj) -> bool:
    return bool(getattr(obj, '__frozen', False))

Try / catch

try:
    obj.my_attr = value
except AttributeError as e:
    if 'cannot add any new attribute' in str(e):
        metadata[id(obj)] = value  # store out-of-band
    else:
        raise

Prevention

When it happens

Trigger: 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).

Common situations: Attempting to attach metadata to a returned/frozen object; library-internal freeze applied to objects the user expected to be mutable.

Related errors


AI-assisted analysis of pandas-dev/pandas@3b7651241d (2026-08-11). Data as JSON: /api/errors/dc42326b4374dbbf. Report an issue: GitHub.

Appendix: source

Thrown at pandas/core/base.py:161

    def _freeze(self) -> None:
        """
        Prevents setting additional attributes.
        """
        object.__setattr__(self, "__frozen", True)

    # prevent adding any attribute via s.xxx.new_attribute = ...
    def __setattr__(self, key: str, value) -> None:
        # _cache is used by a decorator
        # We need to check both 1.) cls.__dict__ and 2.) getattr(self, key)
        # because
        # 1.) getattr is false for attributes that raise errors
        # 2.) cls.__dict__ doesn't traverse into base classes
        if getattr(self, "__frozen", False) and not (
            key == "_cache"
            or key in type(self).__dict__
            or getattr(self, key, None) is not None
        ):
            raise AttributeError(f"You cannot add any new attribute '{key}'")
        object.__setattr__(self, key, value)


class SelectionMixin(Generic[NDFrameT]):
    """
    mixin implementing the selection & aggregation interface on a group-like
    object sub-classes need to define: obj, exclusions
    """

    obj: NDFrameT
    _selection: IndexLabel | None = None
    exclusions: frozenset[Hashable]
    _internal_names = ["_cache", "__setstate__"]
    _internal_names_set = set(_internal_names)

    @final
    @property
    def _selection_list(self):

View on GitHub (pinned to 3b7651241d)