DSPy: The framework for programming—not prompting—language models
Python
Show warning if forward is directly called (#8380)
TomuHirata56efe71595ac
diff --git a/dspy/primitives/program.py b/dspy/primitives/program.pyindex e306591e8..d59c83af7 100644--- a/dspy/primitives/program.py+++ b/dspy/primitives/program.py@@ -1,3 +1,5 @@+import inspect+import loggingfrom typing import Optionalimport magicattr@@ -9,6 +11,7 @@ from dspy.utils.callback import with_callbacksfrom dspy.utils.inspect_history import pretty_print_historyfrom dspy.utils.usage_tracker import track_usage+logger = logging.getLogger(__name__)class ProgramMeta(type):"""Metaclass ensuring every ``dspy.Module`` instance is properly initialised."""@@ -155,6 +158,20 @@ class Module(BaseModule, metaclass=ProgramMeta):results = parallel_executor.forward(exec_pairs)return results+ def __getattribute__(self, name):+ attr = super().__getattribute__(name)++ if name == 'forward' and callable(attr):+ # Check if forward iscalled through __call__+ stack = inspect.stack()+ called_via_call = len(stack) > 1 and stack[1].function == '__call__'++ if not called_via_call:+ logger.warning(f"Calling {self.__class__.__name__}.forward() directly is discouraged. "+ f"Use {self.__class__.__name__}() instead.")++ return attr+def set_attribute_by_name(obj, name, value):magicattr.set(obj, name, value)diff --git a/tests/primitives/test_module.py b/tests/primitives/test_module.pyindex 544146839..023f92c38 100644--- a/tests/primitives/test_module.py+++ b/tests/primitives/test_module.py@@ -489,3 +489,25 @@ async def test_module_history_async():assert len(program.history) == 2assert len(program.cot.history) == 3assert len(program.cot.predict.history) == 3+++def test_forward_direct_call_warning(capsys):+ class TestModule(dspy.Module):+ def forward(self, x):+ return x++ module = TestModule()+ module.forward("test")+ captured = capsys.readouterr()+ assert "Calling TestModule.forward() directly is discouraged" in captured.err+++def test_forward_through_call_no_warning(capsys):+ class TestModule(dspy.Module):+ def forward(self, x):+ return x++ module = TestModule()+ module(x="test")+ captured = capsys.readouterr()+ assert "Calling TestModule.forward() directly is discouraged" not in captured.err