Generator Function)

Source: Internet
Author: User

The generator function is the first available feature in python2.2. It is built in Version 2.3 to support this feature, and yield becomes a keyword, the generator is enhanced in later versions (for example, exception handling is added ). Similar features (iterators) are introduced in C #2.0, which have many similarities. This article discusses ironpython 2.0 beta3.

Any function that contains the yield expression is a generator method, and yield is only used to define a generator method. The generator method is a special method. When you call the generator method, the returned result is not a single value like a common function, but an iterator (equivalent to the system in C. collections. ienumerator interface ). The yield expression returns a value: val = (yield I). The value of Val is the value of the expression. However, this value is not I and is specified by the send (value) method of the call generator. If you do not call this method or call the send (none) method, the return value is none. The returned value of the iterator is the yield Statement (Note yieldExpression[Val = (yield I)] and YieldStatement[Yield I]). When the next ()/send () method of the iterator is called each time, the yield statement immediately returns a value to the caller and saves the currentCodeExecution location and on-site status, and pause execution (in this case, the yield expression has not been executed, that is, Val has not been assigned a value ). When you call the iterator method again, it will resume execution from this position (yield expression) until the next yield expression is encountered again.

The following describes the operation methods supported by the generator:

Next ()

>>>   Def Generate_ints (n ):
For I In Range (n ):
Yield I

>>> Gen = Generate_ints ( 3 )
>>> Gen
< Generator object 0x0000000000000000002b >
>>> GEN. Next ()
0
>>> GEN. Next ()
1
>>> GEN. Next ()
2
>>> GEN. Next ()
Traceback (most recent call last ):
File " <Stdin> " , Line 1 , In   < Module >
Stopiteration: the type is ironpython. runtime. Exceptions. stopiterationexception.
.

After gen. Next () is called, generate_ints () is executed.IValue, which is paused at the yield expression (this example ignores the expression value and only uses the yield Statement ). After gen. Next () is called again, the execution continues from the pause until the next yield expression. When we call gen. Next () 4th times, a stopiteration exception occurs because there is no next yield expression, indicating that the iterator ends.

Send (value) >>>   Def Counter (maximum ):
I = 0
While I < Maximum:
Val = ( Yield I)
# If the yield expression value is set, the counter value is changed.
If Val Is   Not None:
I = Val
Else :
I + = 1

>>> It = Counter ( 10 )
>>>   Print It. Next ()
0
>>>   Print It. Send ( 8 )
8
>>>   Print It. Next ()
9
>>>   Print It. Next ()
Traceback (most recent call last ):
File " <Stdin> " , Line 1 , In   < Module >
Stopiteration: the type is ironpython. runtime. Exceptions. stopiterationexception.
.
>>>

We can see that the return value of the yield expression is specified by the value in send (value. The next ()/send () method enables the generator to continue execution and return the value to the right of the yield statement. The difference is that next () does not contain parameters, therefore, the return value of the yield expression cannot be set (the default value is none ). We can also call send (none), so that the two functions are equivalent.
Note: During the first call, you cannot use the send () method to assign a non-none value because the value is not received by the yield expression. Otherwise, a typeerror exception is thrown: Traceback (most recent call last ):
File " <Stdin> " , Line 1 , In   < Module >
Typeerror: Can ' T send non-none value to a just-started Generator

Throw (type [, value [, traceback])
Throw (type, value = none, traceback = none) is used to raise an exception within the generator. An exception is thrown by the yield expression when the generator is paused. We know that when the generator ends when the yield expression is missing, a stopiteration exception is generated and an exception is ended. We can also use throw () to input an exception to the generator to control the execution of the generator. If the generator does not capture or process the passed-In exception, the exception is returned to the caller. >>>   Def Throw ():
I = 0
While True:
I + = 1
Try :
Yield I
Except Stopiteration, V:
Print   " Caught stopiteration "
# Here is an example of how to capture the exception passed by throw () in the generator,
# Therefore, an exception is returned to the caller and the end generator is used.
Raise V

>>> G = Throw ()
>>> G. Next ()
1
>>> G. Next ()
2
>>> G. Throw (stopiteration)
Caught stopiteration
Traceback (most recent call last ):
File " <Stdin> " , Line 1 , In   < Module >
Stopiteration
>>> G. Next ()
Traceback (most recent call last ):
File " <Stdin> " , Line 1 , In   < Module >
Stopiteration: the type is ironpython. runtime. Exceptions. stopiterationexception.
.
>>>

First, an infinite generator function is defined. When the next () method is called normally, there will always be a return value. When throw (stopiteration) is called to input an end iterator exception, therefore, this exception is caught by the generator and returned to the caller to end the generator. When the next () method is called, The stopiteration exception is thrown.

Close ()
With the introduction of the above throw () method, it is much easier to understand close. This method throws a generatorexit exception when the generator is paused. After this exception is caught inside the generator, the generatorexit or stopiteration exception must be thrown again to make the generator end normally. If a value is returned but not thrown again, the runtimeerror exception is triggered. Multiple close () calls to a generator will not produce errors.

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.