WZMIAOMIAO/deep-learning-for-image-processing · error · AttributeError
'{}' object has no attribute '{}'
Error message
'{}' object has no attribute '{}' What it means
This is the standard Python __getattr__ fallback on a SmoothedValue-style AverageMeter container: attribute lookups first check self.meters, then instance __dict__, and raise AttributeError naming the object type and missing attribute. Any code doing e.g. metric_logger.loss when 'loss' was never logged triggers it.
Source
Thrown at pytorch_keypoint/HRNet/train_utils/distributed_utils.py:137
class MetricLogger(object):
def __init__(self, delimiter="\t"):
self.meters = defaultdict(SmoothedValue)
self.delimiter = delimiter
def update(self, **kwargs):
for k, v in kwargs.items():
if isinstance(v, torch.Tensor):
v = v.item()
assert isinstance(v, (float, int))
self.meters[k].update(v)
def __getattr__(self, attr):
if attr in self.meters:
return self.meters[attr]
if attr in self.__dict__:
return self.__dict__[attr]
raise AttributeError("'{}' object has no attribute '{}'".format(
type(self).__name__, attr))
def __str__(self):
loss_str = []
for name, meter in self.meters.items():
loss_str.append(
"{}: {}".format(name, str(meter))
)
return self.delimiter.join(loss_str)
def synchronize_between_processes(self):
for meter in self.meters.values():
meter.synchronize_between_processes()
def add_meter(self, name, meter):
self.meters[name] = meter
def log_every(self, iterable, print_freq, header=None):View on GitHub (pinned to 1ec3fe6f37)
Solutions
- Check the exact attribute name against the keys registered in meter_dict/update (print(metric_logger.meters.keys())).
- Fix the typo or log the missing metric before accessing it.
- Use getattr(metric_logger, name, default) for optional metrics.
- If this fires for dunder attributes during copy/pickle, add explicit __copy__/__deepcopy__/__getstate__ methods to the class.
- Return None instead of raising if optional semantics are desired (modify __getattr__ fallback).
Example fix
# before print(metric_logger.losses) # AttributeError: 'MetricLogger' object has no attribute 'losses' # after print(metric_logger.loss)
Defensive patterns
Strategy: type-guard
Validate before calling
available = set(metric_logger.meters.keys())
assert "loss" in available, f"'loss' never logged; available: {available}" Type guard
def has_metric(logger, name: str) -> bool:
return name in logger.meters or name in logger.__dict__ Try / catch
try:
value = metric_logger.loss
except AttributeError as e:
logging.warning("Metric missing: %s — using default", e)
value = float("nan") Prevention
- Print metric_logger.meters.keys() once when wiring new metrics.
- Centralize metric name constants shared between train/eval loops.
- Use getattr(logger, name, default) for optional metrics.
When it happens
Trigger: Accessing an attribute on the metric logger that was never added via meters: metric_logger.some_metric before update_loss/meter_dict registered it; typo like metet_logger.lr when only 'lr' was tracked; accessing on a freshly constructed logger with no meters.
Common situations: Typos in metric names between train and eval loops; reading a loss key that differs across model versions; copying tutorial code whose logged keys don't match this repo's; __getattr__ interplay with copy/pickle probing __deepcopy__/__getstate__ which the container lacks.
Related errors
- '{}' object has no attribute '{}'
- '{}' object has no attribute '{}'
- '{}' object has no attribute '{}'
- '{}' object has no attribute '{}'
- '{}' object has no attribute '{}'
AI-assisted analysis of WZMIAOMIAO/deep-learning-for-image-processing@1ec3fe6f37 (2026-08-30).
Data as JSON: /api/errors/f9c7226949460895.
Report an issue: GitHub.