Skip to content

Commit de169d5

Browse files
committed
add sourcecode capture to lazy[]
This works together with `Lazy`, which now takes an optional `sourcecode` argument. It is used as part of the repr; useful for debugging.
1 parent 1a198b9 commit de169d5

File tree

2 files changed

+19
-4
lines changed

2 files changed

+19
-4
lines changed

unpythonic/lazyutil.py

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,11 +34,20 @@ def _init_module(): # called by unpythonic.__init__ when otherwise done
3434
class Lazy:
3535
"""Delayed evaluation, with memoization. (A.k.a. *promise* in Racket.)"""
3636

37-
def __init__(self, thunk):
38-
"""`thunk`: 0-argument callable to be stored for delayed evaluation."""
37+
def __init__(self, thunk, *, sourcecode=None):
38+
"""Create a `Lazy` promise.
39+
40+
`thunk`: 0-argument callable to be stored for delayed evaluation.
41+
42+
`sourcecode`: str, optional, for use by the `lazy[]` macro.
43+
44+
Source code of the thunk, if available. Used in the `repr`,
45+
for debug purposes.
46+
"""
3947
if not callable(thunk):
4048
raise TypeError(f"`thunk` must be a callable, got {type(thunk)} with value {repr(thunk)}")
4149
self.thunk = thunk
50+
self.sourcecode = sourcecode
4251
self.value = _uninitialized
4352
self.thunk_returned_normally = _uninitialized
4453

@@ -62,6 +71,11 @@ def force(self):
6271
else:
6372
raise self.value
6473

74+
def __repr__(self):
75+
if self.sourcecode:
76+
return f'<unpythonic.lazyutil.Lazy object at 0x{id(self):x}, sourcecode="{self.sourcecode}">'
77+
return f"<unpythonic.lazyutil.Lazy object at 0x{id(self):x}, no debug sourcecode>"
78+
6579
def force1(x):
6680
"""Force a ``Lazy`` promise.
6781

unpythonic/syntax/lazify.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,11 @@
77
Starred, keyword, List, Tuple, Dict, Set, Subscript, Load)
88
from functools import partial
99

10-
from mcpyrate.quotes import macros, q, a, h # noqa: F401
10+
from mcpyrate.quotes import macros, q, u, a, h # noqa: F401
1111

1212
from mcpyrate.astfixers import fix_ctx
1313
from mcpyrate.quotes import capture_as_macro, is_captured_value
14+
from mcpyrate.unparser import unparse
1415
from mcpyrate.walkers import ASTTransformer
1516

1617
from .util import (suggest_decorator_index, sort_lambda_decorators, detect_lambda,
@@ -433,7 +434,7 @@ def doit():
433434

434435
# lazy: syntax transformer, lazify a single expression
435436
def _lazy(tree):
436-
return q[h[Lazy](lambda: a[tree])]
437+
return q[h[Lazy](lambda: a[tree], sourcecode=u[unparse(tree)])]
437438

438439
# lazyrec: syntax transformer, recursively lazify elements in container literals
439440
#

0 commit comments

Comments
 (0)