Yield of the Python generator

Source: Internet
Author: User
Tags generator iterable

Reference: "Analysis of Python yield usage", "Python xrange and range", etc.

A function with yield is a generator, which, unlike a normal function, generates a generator that looks like a function call, but does not execute any function code until it calls next () (which is automatically called next () in the For loop) to begin execution. Although the execution process still executes according to the process of the function, each execution to a yield statement is interrupted and an iteration value is returned, and the next execution proceeds from the next statement of yield. It looks as if a function was interrupted several times by yield during normal execution, and each break returns the current iteration value through yield.

The benefits of yield are obvious, and the ability to rewrite a function into a generator yields an iterative capability that computes the value of the next next () rather than the instance of the class, not only the code is concise, but the execution process is exceptionally clear.

First look at range and xrange:

For I in range (+): Pass

The code above generates a List of 1000 elements, and the code:

For I in Xrange (£): Pass

The next value is returned in each iteration, and the memory footprint is small. Because Xrange does not return a List, it returns a generator, (List is an iterative object).

An iterative object can return a iterator object by calling the Iter method, and then for loop access:

class Iterable_:      def __iter__ (self):          return iter ([1, 2, 3])   = iter ((Iterable_ ()))   it:        Print " iterable: " + str (i)    # output   iterable:1  iterable:2   iterable:3
View Code

Range

A = range (0,5) print type (a)    #输出 <type ' list ' >print a          #输出 [0,1,2,3,4]print a[0], a[1] #输出 0, 1

Xrange

A = xrange (0,5) print type (a)    #输出 <type ' xrange ' >print a          #输出 xrange (5) Print a[0], a[1] #输出 0, 1

An iterator is definitely an object of type iterable, which is a special object that contains the next (Python 2) method or the __next__ (Python 3) method and the __iter__ (return self) method. For a generator it must be an iterator that can access its elements through a for loop, but an iterator is not necessarily a generator .

There are two ways to define iterators, the first one is to use the yield keyword, and the other is the generator expression "()". Adding the yield keyword to a method in the method body becomes the generator. Yield function is to return a generator, which will save the current function state, the next time the function is called next run state. When the function does not have the next state of operation, and then continue to call the next method, this time Stopiteration exception is thrown. the generator has the characteristics of iterators, such as only forward traversal. Of course the generator also has its own methods, such as the Send method. You can define values in the current generator by using send. Fibonacci Numbers (Fibonacci)

1. The most common:

def Fab (max):    N, a, b = 0, 0, 1 while    n < Max:        print b        A, B = B, A + b        n = n + 1  

2. To improve the reusability of fab functions, it is best to return a list as follows:

def Fab (max):    N, a, b = 0, 0, 1    L = [] while    n < Max:        l.append (b)        A, B = B, A + b        n = n + 1    return lfor N in Fab (5       

3. The memory consumed by this function will increase with the increase of the parameter max, so it is better not to use list to save the intermediate result, but to iterate through the Iterable object, using iterable we can rewrite the FAB function to a class that supports iterable:

classFab (object):def __init__(self, max): Self.max=Max SELF.N, SELF.A, self.b= 0, 0, 1def __iter__(self):return SelfdefNext (self):ifSELF.N <Self.max:r=self.b self.a, self.b= self.b, SELF.A +self.b SELF.N= SELF.N + 1returnRRaiseStopiteration ()
View Code

The Fab class continuously returns the next number of columns through next (), and memory consumption is always constant:

 for inch Fab (5): ...      Print n . ...
View Code

4. But with this version of the class rewrite, the code is far less concise than the first version of the Fab function. Using yield:

def Fab (max):     N, a, b = 0, 0, 1 while     n < Max:         yield b         # Print B         A, B = B, a +< c19> b         n = n + 1   

As compared to the first version, only print B was changed to yield B, and the call didn't change:

>>> for N in Fab (5):     ... Print n ... 1 1 2) 3 5 

The effect of yield is to turn a function into a Generator,python interpreter to think of it as a generator, and the Call to FAB (5) does not execute the FAB function, but instead returns a Iterable Object! When the For loop executes, each loop executes the code inside the FAB function, and when it executes to yield B, the FAB function returns an iteration value, and the next iteration, the code proceeds from the next statement of Yield B, and the local variable of the function looks exactly the same as before the last break, so the function Continue execution until yield is encountered again.

You can also call the next () Method of Fab (5) Manually (because Fab (5) is a generator object with the next () method) so that we can see more clearly the execution process of the Fab:

>>> f = Fab (5>>>>>>>>>>>>  >>>>>> f.next () Traceback (most recent):  "< stdin>" in <module> stopiteration
View Code

When the function execution finishes, generator automatically throws the Stopiteration exception, indicating that the iteration is complete. In the For loop, there is no need to handle the stopiteration exception and the loop will end normally.

6. How to determine if a function is a special generator function? You can use Isgeneratorfunction to judge:

 from Import  >>> isgeneratorfunction (FAB) True

7. To distinguish between Fab and fab (5), Fab is a generator function, and fab (5) is a generator returned by the call Fab, as is the difference between the definition of a class and an instance of a class:

Import>>>>>> isinstance (Fab (5), types. Generatortype) True

Fab is not iterative, and Fab (5) is iterative:

 from Import  >>>>>> isinstance (Fab (5), iterable) True

Each call to the FAB function generates a new instance of generator, each of which does not affect each other:

>>> f1 = Fab (3) >>> F2 = Fab (5) >>>Print 'F1:', F1.next () F1:1 >>>Print 'F2:', F2.next () F2:1 >>>Print 'F1:', F1.next () F1:1 >>>Print 'F2:', F2.next () F2:1 >>>Print 'F1:', F1.next () F1:2 >>>Print 'F2:', F2.next () F2:2 >>>Print 'F2:', F2.next () F2:3 >>>Print 'F2:', F2.next () F2:5
View Code

The function of return

In a generator function, if there is no return, the default execution to the function is complete, if the return in the execution process, then directly throws Stopiteration terminates the iteration.

Another example

Another example of yield is from file reads. Calling the Read () method directly on a file object causes unpredictable memory consumption. A good approach is to use fixed-length buffers to continuously read the contents of the file. With yield, we no longer need to write an iterative class of read files to easily implement file reads:

def Read_file (Fpath):     = 1024x768    'rb') as F:        while  True:            = F.read (block_size)             if Block:                 yield Block             Else :                 return

The above simply introduces the basic concepts and uses of yield, and yield has a more powerful use in Python 3.

Yield of the Python generator

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.