DSPy: The framework for programming—not prompting—language models
Python
fix(python_interpreter): serialize inf/-inf/nan as valid Python literals (#9991)
Vinay Hipparge385eecc2c891
diff --git a/dspy/primitives/python_interpreter.py b/dspy/primitives/python_interpreter.pyindex b700dfffc..22ad6ce33 100644--- a/dspy/primitives/python_interpreter.py+++ b/dspy/primitives/python_interpreter.py@@ -12,6 +12,7 @@ import inspectimport jsonimport keywordimport logging+import mathimport osimport subprocessimport threading@@ -480,6 +481,10 @@ class PythonInterpreter:elif isinstance(value, bool):# Must check bool before int since bool is a subclass of intreturn "True" if value else "False"+ elif isinstance(value, float) and not math.isfinite(value):+ # str(inf/-inf/nan) returns bare words ("inf", "nan") that are not valid+ # Python literals; wrap them so they evaluate correctly in the sandbox.+ return f"float('{value}')"elif isinstance(value, (int, float)):return str(value)elif isinstance(value, (list, tuple)):diff --git a/tests/primitives/test_python_interpreter.py b/tests/primitives/test_python_interpreter.pyindex 3e523afc0..15d1ae3dc 100644--- a/tests/primitives/test_python_interpreter.py+++ b/tests/primitives/test_python_interpreter.py@@ -31,6 +31,23 @@ def test_user_variable_definitions():assert result == 5, "User variable assignment should work"+def test_non_finite_float_variables():+ """Regression test: inf/-inf/nan variables must be injected as valid Python literals.++ str(float("inf")) is the bare word "inf", which is not a valid Python name, so+ injecting it as `x = inf` previously raised NameError in the sandbox.+ """+ with PythonInterpreter() as interpreter:+ inf_code = "result = 1 if x == float('inf') else 0\nresult"+ assert interpreter.execute(inf_code, variables={"x": float("inf")}) == 1++ neg_inf_code = "result = 1 if x == float('-inf') else 0\nresult"+ assert interpreter.execute(neg_inf_code, variables={"x": float("-inf")}) == 1++ nan_code = "import math\nresult = 1 if math.isnan(x) else 0\nresult"+ assert interpreter.execute(nan_code, variables={"x": float("nan")}) == 1++def test_rejects_python_keywords_as_variable_names():"""Test that Python keywords are rejected as variable names."""with PythonInterpreter() as interpreter: