keras-team/keras · error · RuntimeError

You forgot to call `super().__init__()` in the `__init__()`

Error message

You forgot to call `super().__init__()` in the `__init__()` method. Go add it!

What it means

Keras Metric objects must call super().__init__() in their __init__ before anything else, because that call installs the _tracker used to register metric variables. add_variable() and __call__() both call _check_super_called(), which raises this RuntimeError when _tracker is missing. It almost always means a custom metric subclass skipped or deferred the parent constructor.

Source

Thrown at keras/src/metrics/metric.py:245

        return self.result()

    def get_config(self):
        """Return the serializable config of the metric."""
        return {"name": self.name, "dtype": self.dtype}

    @classmethod
    def from_config(cls, config):
        return cls(**config)

    def __setattr__(self, name, value):
        # Track Variables, Layers, Metrics
        if hasattr(self, "_tracker"):
            value = self._tracker.track(value)
        return super().__setattr__(name, value)

    def _check_super_called(self):
        if not hasattr(self, "_tracker"):
            raise RuntimeError(
                "You forgot to call `super().__init__()` "
                "in the `__init__()` method. Go add it!"
            )

    def __repr__(self):
        return f"<{self.__class__.__name__} name={self.name}>"

    def __str__(self):
        return self.__repr__()

View on GitHub (pinned to 7a34a03db6)

Solutions

  1. Add super().__init__(name=..., dtype=...) as the first statement of your __init__.
  2. If using multiple inheritance, ensure keras.metrics.Metric's __init__ runs before add_variable is called.
  3. Verify you subclass keras.metrics.Metric and no intermediate base class swallows __init__.

Example fix

# before
class MyMetric(keras.metrics.Metric):
    def __init__(self):
        self.total = self.add_variable(name='total', initializer='zeros')

# after
class MyMetric(keras.metrics.Metric):
    def __init__(self, name='my_metric', **kwargs):
        super().__init__(name=name, **kwargs)
        self.total = self.add_variable(name='total', initializer='zeros')
Defensive patterns

Strategy: validation

Validate before calling

class MyMetric(keras.metrics.Metric):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)  # must be first statement

Type guard

def is_initialized_metric(m) -> bool:
    import keras
    return isinstance(m, keras.metrics.Metric) and hasattr(m, '_tracker')

Prevention

When it happens

Trigger: Defining a custom class inheriting from keras.metrics.Metric whose __init__ does not call super().__init__() (or calls it lazily/conditionally), then calling self.add_variable(...) or invoking the metric via metric(y_true, y_pred).

Common situations: Porting old tf.keras custom metrics, multi-inheritance wrappers where __init__ chains break, or refactoring __init__ and accidentally removing the super() call.

Related errors


AI-assisted analysis of keras-team/keras@7a34a03db6 (2026-08-25). Data as JSON: /api/errors/6af9b09f671a65f1. Report an issue: GitHub.