<p>不幸的是,据我所知,Python中没有简单或惯用的对等词“sow”和“reap”。但是,您可能可以使用生成器和装饰器的组合来伪造它,如下所示:</p>
<pre><code>def sow(func):
class wrapper(object):
def __call__(self, *args, **kwargs):
output = list(func(*args, **kwargs))
return output[-1]
def reap(self, *args, **kwargs):
output = list(func(*args, **kwargs))
final = output[-1]
intermediate = output[0:-1]
return [final, intermediate]
return wrapper()
@sow
def f(seq, mul):
yield seq
yield mul
yield [a * mul for a in seq]
print f([1, 2, 3], 4) # [4, 8, 12]
print f.reap([1, 2, 3], 4) # [[4, 8, 12], [[1, 2, 3], 4]]
</code></pre>
<p>然而,与Mathematica相比,这种方法有一些局限性。首先,必须重写该函数,使其使用<code>yield</code>而不是return,将其转换为生成器。最后产生的值就是最终的输出。在</p>
<p>它也没有文档描述的“异常”类属性。decorator <code>@sow</code>只是返回一个类,该类看上去像一个函数,并添加了一个额外的参数<code>reap</code>。在</p>
<hr/>
<p>另一种解决方案可能是尝试使用<a href="https://github.com/lihaoyi/macropy" rel="nofollow">macropy</a>。因为它直接操作Python的AST和字节码,所以您可能能够将对更符合您所寻找的内容的直接支持组合在一起。<a href="https://github.com/lihaoyi/macropy#tracing" rel="nofollow">tracing</a>宏在意图上与您想要的类似。在</p>