WZMIAOMIAO/deep-learning-for-image-processing · error · AttributeError

'{}' object has no attribute '{}'

Error message

'{}' object has no attribute '{}'

What it means

MeterLibrary (the averaged-meters container) implements __getattr__ that looks the attribute up in self.meters, then self.__dict__, and finally raises AttributeError naming the type and missing attribute. It means you accessed e.g. library.some_metric when no meter with that name was registered (or was registered under a different key).

Source

Thrown at pytorch_object_detection/yolov3_spp/train_utils/distributed_utils.py:162

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

  1. Confirm the meter was registered: call meter_library.update(loss_name=value) before reading it.
  2. Print meter_library.meters.keys() to see the exact registered names and fix the access spelling.
  3. Guard access with hasattr(meter_library, 'loss') or use meter_library.meters.get('loss') to avoid AttributeError.

Example fix

// before
print(metric_logger.lr, metric_logger.los)
// after
print(metric_logger.lr, metric_logger.loss)
Defensive patterns

Strategy: type-guard

Validate before calling

known = set(metric_logger.meters.keys())
assert 'loss' in known, f"meter not registered; have: {known}"

Type guard

def has_meter(lib, name: str) -> bool:
    return name in getattr(lib, 'meters', {})

Try / catch

try:
    avg_loss = metric_logger.loss
except AttributeError:
    avg_loss = float('nan')  # or register the meter before reading

Prevention

When it happens

Trigger: Accessing an attribute on the meter wrapper (e.g. in distributed_utils or the training loop like metric_logger.loss) when self.meters has no key with that exact name — meter never created via meter_library.update(..., n=...) or misspelled key.

Common situations: Typo in the metric name at access time vs update time; reading a meter before the first update call registered it; code copied between models that track different loss names.

Related errors


AI-assisted analysis of WZMIAOMIAO/deep-learning-for-image-processing@1ec3fe6f37 (2026-08-30). Data as JSON: /api/errors/225e45b17dc2daa3. Report an issue: GitHub.