如何将惰性变量传递给函数参数,而无需对其进行求值,除非返回 [英] How to pass lazy variables to a functions parameters without them being evaluated unless returned
问题描述
这个问题是针对python的,尽管我不介意用户分享其他语言的经验.
This question is aimed at python, although I don't mind users sharing experience from other languages.
基本上,我的问题是尝试将惰性变量传递给函数. (就我而言,我可能无法控制该功能,因此无法将其更改为将生成器作为输入).
Basically my problem is trying to pass lazy variables to a function. (in my case i may have no control over the function, so can't change it to take a generator as input).
示例(请注意dict.get是一个函数示例,但很可能是foo)
Example (note that dict.get is an example of a function, but it could well be foo)
def calc():
sleep(10**100)
return 42
def my_args():
yield 'meaning'
yield calc()
#Instead of
meaning_of_life = dict_.get('meaning', calc())
#I would rather
meaning_of_life = dict_.get(my_args)
我不认为有任何一种优雅的解决方案?可能需要复杂的猴子修补程序吗? (如果是这样,那么我不值得尝试).
I don't suppose there are any one line elegant solutions? Possibly complicated monkey patching is required? (if so it's not worth it for me to try).
谢谢.
推荐答案
您可以使用特殊的对象将计算推迟到首次使用该对象之前.看起来惰性代理可以满足您的要求.
You can use a special object to defer computation until the object is first used. It looks a Lazy Proxy will do what you want.
这篇关于如何将惰性变量传递给函数参数,而无需对其进行求值,除非返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!