Python: generator expression vs. yield

前端 未结 8 784
悲哀的现实
悲哀的现实 2020-12-07 08:43

In Python, is there any difference between creating a generator object through a generator expression versus using the yield statement?

8条回答
  •  北荒
    北荒 (楼主)
    2020-12-07 08:47

    In this example, not really. But yield can be used for more complex constructs - for example it can accept values from the caller as well and modify the flow as a result. Read PEP 342 for more details (it's an interesting technique worth knowing).

    Anyway, the best advice is use whatever is clearer for your needs.

    P.S. Here's a simple coroutine example from Dave Beazley:

    def grep(pattern):
        print "Looking for %s" % pattern
        while True:
            line = (yield)
            if pattern in line:
                print line,
    
    # Example use
    if __name__ == '__main__':
        g = grep("python")
        g.next()
        g.send("Yeah, but no, but yeah, but no")
        g.send("A series of tubes")
        g.send("python generators rock!")
    

提交回复
热议问题