Lightning-AI/pytorch-lightning · error · AttributeError
'{type(self).__name__}' object has no attribute '{key}'
Error message
'{type(self).__name__}' object has no attribute '{key}' What it means
This class is a dict subclass whose `__getattr__` maps attribute access to key lookup (`self[key]`). When code accesses an attribute that is neither a real attribute nor a key in the dict, the KeyError is converted into a standard AttributeError with the class and key name, matching Python's normal attribute-error semantics.
Source
Thrown at src/lightning/fabric/utilities/data.py:494
>>> import torch
>>> model = torch.nn.Linear(2, 2)
>>> state = AttributeDict(model=model, iter_num=0)
>>> state.model
Linear(in_features=2, out_features=2, bias=True)
>>> state.iter_num += 1
>>> state.iter_num
1
>>> state
"iter_num": 1
"model": Linear(in_features=2, out_features=2, bias=True)
"""
def __getattr__(self, key: str) -> Any:
try:
return self[key]
except KeyError as e:
raise AttributeError(f"'{type(self).__name__}' object has no attribute '{key}'") from e
def __setattr__(self, key: str, val: Any) -> None:
self[key] = val
def __delattr__(self, item: str) -> None:
if item not in self:
raise KeyError(item)
del self[item]
def __repr__(self) -> str:
if not len(self):
return ""
max_key_length = max(len(str(k)) for k in self)
tmp_name = "{:" + str(max_key_length + 3) + "s} {}"
rows = [tmp_name.format(f'"{n}":', self[n]) for n in sorted(self.keys())]
return "\n".join(rows)
View on GitHub (pinned to 9fed5c27d2)
Solutions
- Check membership before access: `if 'key' in obj:` or `obj.get('key', default)`.
- Use explicit key access `obj['key']` with KeyError handling, or verify available keys via `list(obj.keys())`.
- Regenerate/re-save the dict so expected keys exist; align key names across versions.
Example fix
# before
value = cfg.learning_rate # AttributeError if key absent
# after
value = cfg.get('learning_rate', default_lr) Defensive patterns
Strategy: type-guard
Validate before calling
if 'learning_rate' in cfg:
lr = cfg['learning_rate']
else:
lr = default_lr Type guard
def has_key(cfg, key: str) -> bool:
return isinstance(cfg, dict) and key in cfg Try / catch
try:
lr = cfg.learning_rate
except AttributeError:
lr = default_lr Prevention
- Treat attribute-dicts like dicts: use .get() or membership checks.
- Print sorted(obj.keys()) when debugging config access failures.
- Pin config key names with constants shared across versions.
When it happens
Trigger: Accessing a missing attribute on Lightning's dict-like wrapper (e.g. `_AttributeDict`): `cfg.some_missing_key`, where 'some_missing_key' was never inserted into the dict.
Common situations: Reading configuration/hyperparameter objects (e.g. `hparams` or saved checkpoints restored into an attribute-dict) where a key was renamed between versions or never saved; typos in config key access.
Related errors
- You cannot set both `activation_checkpointing` and `activati
- Device should be CPU, got {device} instead.
- `devices` selected with `CPUAccelerator` should be an int >
- Device should be CUDA, got {device} instead.
- You requested to find {num_devices} devices but there are no
AI-assisted analysis of Lightning-AI/pytorch-lightning@9fed5c27d2 (2026-08-28).
Data as JSON: /api/errors/82f31ed409209d43.
Report an issue: GitHub.