In-depth study of python yield, generator, and pythonyield

Source: Internet
Author: User

In-depth study of python yield, generator, and pythonyield

Preface
It is hard to say that you will do things you have never used and that you have never understood. Although I have been familiar with the concept of python coroutine before, I am just taking a look at it. During a conversation these two days, when someone asks about the coroutine, I can't remember what I 've seen, later, I suddenly thought of yield, but it was too late. I can only say that the concept is unclear. So this article first gets a glimpse of the python generator and yield keywords.

What is a generator?
1. the generator is a special program that can be used to control the iterative behavior of loops.
2. the generator is similar to a function whose return value is an array. This function can receive parameters and be called. However, unlike normal functions, it returns an array containing all values at once, the generator generates only one value at a time, which greatly reduces the number of inner and crude values, and allows calling a function to quickly start processing the first few return values. Therefore, the generator looks like a function but acts like an iterator.
Generator in python
Python provides two basic methods.

1) generator function: it is also defined by def. The keyword yield is used to return a result at a time, blocking and restarting.
2) generator expression: returns an object that generates results only when necessary.
The following describes in detail.

1. Generator Functions
Why is it called a generator function? Because it generates a numerical queue over time. After a general function is executed, a value is returned and then exited. However, the generator function is automatically suspended and then re-picked up for execution. Then, the function is disabled using the yield keyword, return a value to the caller and retain enough of the Current Status to continue the function execution. The generator is closely related to the iteration protocol. every iteration object has a _ next () _ member method. This method either returns the next iteration, or cause an exception to end the iteration.
To support iterative protocolsYieldThe function of a statement is compiled as a generator. When a function is called, a generator object is returned. The returned object supports iterative interfaces, that is, the member method _ next () _ continues to execute from the break.
See the following example:

# codesdef create_counter(n): print "create counter" while True:  yield n  print 'increment n'  n += 1cnt = create_counter(2)print cntprint next(cnt)print next(cnt)# output<generator object create_counter at 0x0000000001D141B0>create counter2increment n3

Analyze this example:

  • The keyword yield appears in the create_counter function, indicating that this function generates only one result value each time. This function returns a generator (which can be seen through the first line of output) to generate continuous n values.
  • When creating a generator instance, you only need to call it like a normal function, but this call does not execute this function. This can be seen through the output.
  • The next () function uses the generator object as its own parameter. During the first call, it executes the create_counter () function to the yield statement and returns the resulting value 2.
  • We call the next () function repeatedly, and execute it from the last suspended place until the yield keyword is encountered again.

For a deeper understanding, let's take another example.

#codingdef cube(n): for i in range(n):  yield i ** 3for i in cube(5): print i#output0182764

Therefore, from the perspective of understanding the function, we can compare yield to return, but the function is indeed completely different. In the for loop, the next () function is called every time the iteration rule is automatically followed, therefore, the above results are not difficult to understand.

2. Generator expression
The generator expression comes from the combination of iteration and list parsing. For more information about the concepts and usage of list parsing, see my previous blog. The generator expression is similar to list parsing, but he uses angle brackets instead of square brackets. The following code:

>>># List resolution generation list >>> [x ** 3 for x in range (5)] [0, 1, 8, 27, 64] >>>>># generator expression >>> (x ** 3 for x in range (5 )) <generator object <genexpr> at 0x000000000315F678 >>># conversion between the two >>> list (x ** 3 for x in range (5) [0, 1, 8, 27, 64]

In terms of operations, it is very inconvenient to use a large number of next () functions in the generator table, and the for Loop will automatically start the next function, so you can use it as follows:

>>> for n in (x ** 3 for x in range(5)): print('%s, %s' % (n, n * n)) 0, 01, 18, 6427, 72964, 4096>>> 

Comparison between the two
An Iteration can be written as either a generator function or a coroutine generator expression. Both automatic and manual iterations are supported. These generators only support one active iteration, that is, the generator's iterator is the generator itself.

Summary
I think of what I often say when I was in junior high school. It's better to do it manually.

Articles you may be interested in:
  • Python in-depth understanding of yield
  • How to Use the python Generator
  • Python yield usage example
  • How to use yield in python
  • Example of a random password dictionary Generator Implemented in python
  • Python iterator and generator instance details
  • Generator and yield in Python
  • Python Generator (Generator)
  • Example of python generator usage

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.