Is there a Python idiom for evaluating a list of functions/expressions with short-circuiting?

南笙酒味 提交于 2019-12-04 03:52:59
Katriel

Use a generator expression:

rules = [ rule1, rule2, rule3, rule4, ... ]
rules_generator = ( r( solution ) for r in rules )
return all( rules_generator )

Syntactic sugar: you can omit the extra parentheses:

rules = [ rule1, rule2, rule3, rule4, ... ]
return all( r( solution ) for r in rules )

A generator is (basically) an object with a .next() method, which returns the next item in some iterable. This means they can do useful things like read a file in chunks without loading it all into memory, or iterate up to huge integers. You can iterate over them with for loops transparently; Python handles it behind-the-scenes. For instance, range is a generator in Py3k.

You can roll your own custom generator expressions by using the yield statement instead of return in a function definition:

def integers():
    i = 0
    while True:
        yield i

and Python will handle saving the function's state and so on. They're awesome!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!