DSPy: The framework for programming—not prompting—language models
Python
fix(dspy): keep fields when copying an Example with no visible fields (#10637)
Edson93bfb72891fa
diff --git a/dspy/primitives/example.py b/dspy/primitives/example.pyindex 0fec74c03..c0b5825e8 100644--- a/dspy/primitives/example.py+++ b/dspy/primitives/example.py@@ -109,7 +109,7 @@ class Example:self._input_keys = None# Initialize from a base Example if provided- if base and isinstance(base, type(self)):+ if 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.@@ -119,7 +119,7 @@ class Example:self._input_keys = set(base_input_keys)# Initialize from a dict if provided- elif base and isinstance(base, dict):+ elif isinstance(base, dict):self._store = base.copy()# Update with provided kwargsdiff --git a/tests/primitives/test_example.py b/tests/primitives/test_example.pyindex 715304370..22d5c0348 100644--- a/tests/primitives/test_example.py+++ b/tests/primitives/test_example.py@@ -160,6 +160,19 @@ def test_example_copy_preserves_input_keys():assert Example(base=example)._input_keys == {"question"}+def test_example_copy_preserves_fields_when_example_has_no_visible_fields():+ # An Example whose only contents are `dspy_*` metadata or an input/label split has len() == 0.+ # Copying it must still carry over its store and input keys.+ template = Example().with_inputs("question")+ filled = template.copy(question="q", answer="a")+ assert filled._input_keys == {"question"}+ assert filled.inputs().toDict() == {"question": "q"}++ metadata_only = Example(dspy_uuid="u1", dspy_split="train")+ assert metadata_only.copy().toDict() == {"dspy_uuid": "u1", "dspy_split": "train"}+ assert Example(base=metadata_only).toDict() == {"dspy_uuid": "u1", "dspy_split": "train"}++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