Skip to content

armgit / dspy

Public Imported from GitHub
0

DSPy: The framework for programming—not prompting—language models

Python

Preserve input/label split when copying an Example (#9946)

Shardul Deshpande735b2d6a003f
diff --git a/dspy/primitives/example.py b/dspy/primitives/example.py
index 40eb1c18d..ce58f4af3 100644
--- a/dspy/primitives/example.py
+++ b/dspy/primitives/example.py
@@ -111,6 +111,12 @@ class Example:
# Initialize from a base Example if provided
if base and isinstance(base, type(self)):
self._store = base._store.copy()
+ # Preserve the input/label split so copy()/without()/Example(base=...)
+ # don't silently break .inputs()/.labels() on the new instance.
+ # Use getattr: subclasses such as Prediction don't keep _input_keys.
+ base_input_keys = getattr(base, "_input_keys", None)
+ if base_input_keys is not None:
+ self._input_keys = set(base_input_keys)
# Initialize from a dict if provided
elif base and isinstance(base, dict):
diff --git a/tests/primitives/test_example.py b/tests/primitives/test_example.py
index c569016db..e100012bf 100644
--- a/tests/primitives/test_example.py
+++ b/tests/primitives/test_example.py
@@ -120,6 +120,36 @@ def test_example_copy_without():
_ = without_a.a
+def test_example_copy_preserves_input_keys():
+ """copy()/without() must preserve the input/label split.
+
+ Regression: the input keys were reset to None on copy, so .inputs()/.labels()
+ raised on any copied Example (and Example(base=other) lost the split too).
+ """
+ example = Example(question="q", answer="a").with_inputs("question")
+
+ copied = example.copy(answer="b")
+ assert copied._input_keys == {"question"}
+ assert copied.inputs().toDict() == {"question": "q"}
+ assert copied.labels().toDict() == {"answer": "b"}
+
+ # without() routes through copy(); the split must survive for remaining fields.
+ no_extra = example.copy(source="web").without("source")
+ assert no_extra._input_keys == {"question"}
+ assert no_extra.inputs().toDict() == {"question": "q"}
+
+ # Constructing directly from an Example base also preserves the split.
+ assert Example(base=example)._input_keys == {"question"}
+
+
+def test_prediction_copy_does_not_require_input_keys():
+ # Example subclasses (e.g. Prediction) don't keep _input_keys; copy() must not crash.
+ import dspy
+
+ copied = dspy.Prediction(answer="a").copy(answer="b")
+ assert copied.answer == "b"
+
+
def test_example_to_dict():
example = Example(a=1, b=2)
assert example.toDict() == {"a": 1, "b": 2}