Skip to content

Commit 1fb91b1

Browse files
Fix None appearing when print expression is last line (#8)
1 parent 534205e commit 1fb91b1

File tree

2 files changed

+40
-23
lines changed

2 files changed

+40
-23
lines changed

src/mcp_django_shell/shell.py

Lines changed: 27 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -202,29 +202,33 @@ def __post_init__(self):
202202

203203
@property
204204
def output(self) -> str:
205-
value = repr(self.value)
206-
207-
if (
208-
self.value is not None
209-
and hasattr(self.value, "__iter__")
210-
and not isinstance(self.value, str | dict)
211-
):
212-
# Format querysets and lists nicely, overwriting `value` if successful
213-
try:
214-
items = list(self.value)
215-
match len(items):
216-
case 0:
217-
value = "Empty queryset/list"
218-
case n if n > 10:
219-
formatted = "\n".join(repr(item) for item in items[:10])
220-
value = f"{formatted}\n... and {n - 10} more items"
221-
case _:
222-
value = "\n".join(repr(item) for item in items)
223-
except Exception:
224-
# If iteration fails for any reason, just use the repr
225-
pass
226-
227-
return self.stdout + value or value
205+
parts = []
206+
207+
if self.stdout:
208+
parts.append(self.stdout.strip())
209+
210+
if self.value is not None:
211+
if hasattr(self.value, "__iter__") and not isinstance(
212+
self.value, str | dict
213+
):
214+
# Format querysets and lists nicely
215+
try:
216+
items = list(self.value)
217+
match len(items):
218+
case 0:
219+
parts.append("Empty queryset/list")
220+
case n if n > 10:
221+
parts.extend(repr(item) for item in items[:10])
222+
parts.append(f"... and {n - 10} more items")
223+
case _:
224+
parts.extend(repr(item) for item in items)
225+
except Exception:
226+
# If iteration fails, fall back to repr
227+
parts.append(repr(self.value))
228+
else:
229+
parts.append(repr(self.value))
230+
231+
return "\n".join(parts)
228232

229233

230234
@dataclass

tests/test_shell.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,19 @@ def test_execute_print_captures_stdout(self, shell):
154154
assert result.value is None
155155
assert "Hello, World!" in result.output
156156

157+
def test_multiline_ending_with_print_no_none(self, shell):
158+
code = """
159+
x = 5
160+
y = 10
161+
print(f"Sum: {x + y}")
162+
"""
163+
result = shell._execute(code.strip())
164+
165+
assert isinstance(result, ExpressionResult)
166+
assert result.value is None
167+
assert "Sum: 15" in result.output
168+
assert result.output == "Sum: 15"
169+
157170
def test_execute_invalid_code_returns_error(self, shell):
158171
result = shell._execute("1 / 0")
159172

0 commit comments

Comments
 (0)