A summary of the usage of Python yield and yield from

Time:2021-2-5

Usage Summary of Python yield and yield from

Yield effect: 1

Note:The next () method of generator is next () in Python 2, but not in Python 3__next__()[there are two underscores before and after next]

Turn a function into a generator, and the function with yield is no longer an ordinary function. That is: a function with yield is a generator, which is different from ordinary functions. Generating a generator looks like a function call, but it will not execute any function code until it calls next () (which will be called automatically in the for loop). Although the execution process is still executed according to the function process, every time a yield statement is executed, it will be interrupted and an iteration value will be returned. The next execution will continue from the next yield statement. It looks like a function is interrupted several times by yield during normal execution. Each interrupt will return the current iteration value through yield.

The advantage of yield is obvious. Rewriting a function as a generator can obtain the iterative ability. Compared with using the instance of a class to save the state to calculate the next () value, the code is not only concise, but also the execution process is extremely clear.

Using print to print fiborachet series — Basic Edition

#!/usr/bin/env python
# -*- coding: utf-8 -*-

def fab(max):
    n , a, b = 0, 0 , 1
    while n < max:
        print(b)
        a, b = b, a + b
        n = n + 1

if __name__ == '__main__':
    fab(6)  # 1 1 2 3 5 8

Using yield to print fibolacci series

#!/usr/bin/env python
# -*- coding: utf-8 -*-

def fab(max):
    n , a, b = 0, 0 , 1
    while n < max:
        yield b
        a, b = b, a + b
        n = n + 1

if __name__ == '__main__':
    for n in fab(6): # 1 1 2 3 5 8
        print(n)

How to judge whether a function is a special generator function

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from inspect import isgeneratorfunction

def fab(max):
    n , a, b = 0, 0 , 1
    while n < max:
        yield b
        a, b = b, a + b
        n = n + 1

if __name__ == '__main__':
    f1 = fab(3)#True fab is a generatorfunction
    print(isgeneratorfunction(fab))

    # False fab(3)It's not a generatorfunction
    # And fab(3)Is a generator returned by calling fabprint(isgeneratorfunction(fab(3)))

Read large file with yield

#!/usr/bin/env python
# -*- coding: utf-8 -*-

def read_file(fpath):
    BLOCK_SIZE = 100
    with open(fpath, "rb") as f:
        while True:
            block = f.read(BLOCK_SIZE)
            if block:
                yield block
            else:
                return

if __name__ == '__main__':
    fpath = "/home/exercise-python3.7.1/vote/mysite/mysite/polls/test.txt"
    read_gen = read_file(fpath)

    print(read_gen.__next__())
    print(read_gen.__next__())
    print(read_gen.__next__())
    print(read_gen.__next__())

    # forThe loop automatically calls the__ next__()Method, so the output effect is the same as above4Print,4A print will test.[output of contents in txt]for data in read_gen:
        print(data)

Comparison of yield and yield from

Stitching iterative objects using yield

#!/usr/bin/env python
# -*- coding: utf-8 -*-

if __name__ == '__main__':
    astr = "ABC"
    alist = [1, 2, 3]
    adict = {"name": "wangbm", "age": 18}
    # generate
    agen = (i for i in range(4, 8))

    def gen(*args, **kw):
        for item in args:
            for i in item:
                yield i

    new_list = gen(astr, alist, adict, agen)
    print(list(new_list))
    # ['A', 'B', 'C', 1, 2, 3, 'name', 'age', 4, 5, 6, 7]

Using yield from to splice iteratable objects

#!/usr/bin/env python
# -*- coding: utf-8 -*-

if __name__ == '__main__':
    astr = "ABC"
    alist = [1, 2, 3]
    adict = {"name": "wangbm", "age": 18}
    # generate
    agen = (i for i in range(4, 8))

    def gen(*args, **kw):
        for item in args:
            yield from item

    new_list = gen(astr, alist, adict, agen)
    print(list(new_list))
    # ['A', 'B', 'C', 1, 2, 3, 'name', 'age', 4, 5, 6, 7]

Conclusion

From the comparison of the above two methods, we can see that yield from is followed by an iterative object, which can yield each element of the iterative object one by one. Compared with yield, the code is more concise and the structure is clearer.

image.png

reference material:

  www.cnblogs.com/wongbingming/p/9085…

  www.cnblogs.com/python-life/articl…

Author: Hibiscus, 2013

Link:www.jianshu.com/p/bd8563093561

This work adoptsCC agreementReprint must indicate the author and the link of this article

Recommended Today

[Q & A share the second bullet] MySQL search engine, after watching the tyrannical interviewer!

Hello, I’m younger brother. A few days ago, I shared the second interview question, the interview site of search engine in MySQL. This question is the interview at normal temperature. After reading it, I’m sure you will gain something in terms of database engine If you haven’t read my first share, you can refer to […]