Skip to content

Commit 9b2e1c6

Browse files
authored
fix module base init via metaclass (#8307)
1 parent 2f18c84 commit 9b2e1c6

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

dspy/primitives/program.py

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,32 @@
1111

1212

1313
class ProgramMeta(type):
14-
pass
14+
"""Metaclass ensuring every ``dspy.Module`` instance is properly initialised."""
15+
16+
def __call__(cls, *args, **kwargs):
17+
# Create the instance without invoking ``__init__`` so we can inject
18+
# the base initialization beforehand.
19+
obj = cls.__new__(cls, *args, **kwargs)
20+
if isinstance(obj, cls):
21+
# ``_base_init`` sets attributes that should exist on all modules
22+
# even when a subclass forgets to call ``super().__init__``.
23+
Module._base_init(obj)
24+
cls.__init__(obj, *args, **kwargs)
25+
26+
# Guarantee existence of critical attributes if ``__init__`` didn't
27+
# create them.
28+
if not hasattr(obj, "callbacks"):
29+
obj.callbacks = []
30+
if not hasattr(obj, "history"):
31+
obj.history = []
32+
return obj
1533

1634

1735
class Module(BaseModule, metaclass=ProgramMeta):
1836
def _base_init(self):
1937
self._compiled = False
38+
self.callbacks = []
39+
self.history = []
2040

2141
def __init__(self, callbacks=None):
2242
self.callbacks = callbacks or []

0 commit comments

Comments
 (0)