Skip to content

Commit 24feac4

Browse files
committed
lispy-python.py (print_elisp): Improve and add test
1 parent 97f73df commit 24feac4

File tree

2 files changed

+27
-6
lines changed

2 files changed

+27
-6
lines changed

lispy-python.py

+9-6
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,9 @@ def format_arg(arg_pair: Tuple[str, Optional[str]]) -> str:
195195

196196
def print_elisp(obj: Any, end: str = "\n") -> None:
197197
if hasattr(obj, "_asdict") and obj._asdict is not None:
198+
if hasattr(type(obj), "__repr__"):
199+
print('"' + str(obj).replace('"', '') + '"')
200+
return
198201
# namedtuple
199202
try:
200203
print_elisp(obj._asdict(), end)
@@ -230,14 +233,14 @@ def print_elisp(obj: Any, end: str = "\n") -> None:
230233
print_elisp(list(obj))
231234
elif isinstance(obj, int):
232235
print(obj)
236+
elif isinstance(obj, list) or isinstance(obj, tuple):
237+
print("(", end="")
238+
for x in obj:
239+
print_elisp(x)
240+
print(")")
233241
else:
234242
if obj is not None:
235-
if type(obj) is list or type(obj) is tuple:
236-
print("(", end="")
237-
for x in obj:
238-
print_elisp(x)
239-
print(")")
240-
elif type(obj) is str:
243+
if type(obj) is str:
241244
# quote strings?
242245
# print("\"'" + re.sub("\"", "\\\"", obj) + "'\"", end=" ")
243246
print('"' + re.sub("\"", "\\\"", obj) + '"', end=" ")

test/test_lispy-python.py

+18
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import io
22
import os
3+
import re
34
import ast
45
import sys
56
from importlib.machinery import SourceFileLoader
@@ -8,6 +9,12 @@
89

910
lp = SourceFileLoader("lispy-python", os.path.dirname(__file__) + "/../lispy-python.py").load_module()
1011

12+
def print_elisp_to_str(obj):
13+
with io.StringIO() as buf, redirect_stdout(buf):
14+
lp.print_elisp(obj)
15+
return buf.getvalue().strip()
16+
17+
1118
def with_output_to_string(code):
1219
with io.StringIO() as buf, redirect_stdout(buf):
1320
exec(code)
@@ -206,3 +213,14 @@ def square(x):
206213
assert r["out"] == '(3\n4\n5\n)'
207214
assert lp.select_item(code, 0) == 3
208215
assert lp.select_item(code, 1) == 4
216+
217+
def test_eval_syntax_error():
218+
r = lp.eval_code("[[]", {})
219+
assert "SyntaxError" in r["err"]
220+
221+
def test_print_elisp():
222+
class Obj(object):
223+
pass
224+
arr = [Obj()]
225+
r = print_elisp_to_str(arr)
226+
assert re.match('\\("<.*Obj object at 0x[0-9a-f]+>" \\)', r)

0 commit comments

Comments
 (0)