Yield and yield from

Source: Internet
Author: User

Yield

Yield returns a generator that yields both a value and a value, yielding can use next () to start the generator, and send a value to the generator at the same time, and then invoke next () or send (None) to activate the generator when the generator is first started. A yield corresponds to a send or next (), which throws stopiteration when the number of send or next () exceeds the yield number

1 defGen_yield ():2Value =yield13     Print(value)4Value =yield25     Print(value)6Value =yield37     Print(value)8     return "End"9 Ten  OneGen =Gen_yield () A  - Print(Next (gen)) - Print(Gen.send ("a")) the Print(Gen.send ("b")) - Print(Gen.send ("C"))

Next (gen) activates the generator yield 1, returns 1, and suspends the generator gen.send ("a") passes "a" to value = yield 1, at which time value= "a", prints A, returns 2, suspends the generator; Gen.send ("B") passes "B" to value = Yield 2, at which time value= "B", prints "B" and returns 3, suspends the generator, gen.send ("C") passes "C" to value = Yield 3, at which time value= "C" , print "C", which throws a stopiteration exception because there are no generators behind it.

1a2b3ctraceback (most recent call last):    Print(gen.send ("C  ")) Stopiteration:end

Close ()/throw () Close/Pause generator

1 defGen_yield ():2     Try:3         yield "a"4     exceptstopiteration:5         Pass6     yield "b"7     yield "C"8     return "End"9 Ten  OneGen =Gen_yield () A  - Print(Next (gen)) - gen.close () the Print(111) - Print(Next (Gen))

Close () Closes the generator, and the yield-related statement is no longer executed when the generator executes the close () method, even if the exception is handled.

throw () equals the interrupt, pause generator, throws an exception through throw (), and after exception processing the generator executes the next yield, and the next yield is no longer affected by the throw ().

1 defGen_yield ():2     Try:3         yield "a"4     exceptException:5         Pass6     yield "b"7     yield "C"8     return "End"9 Ten  OneGen =Gen_yield () A  - Print(Next (gen)) - Print(Gen.throw (Exception)) the Print(111) - Print(Next (Gen))

Result

AB111C

Yield from

Yield from is similar to yield, but yield from is followed by an iterative object that returns the Iter,yield of the iteration object directly to the accepted object

defGen_yield (iterable):yielditerabledefGen_yield_from (iterable):yield  fromiterable forValueinchGen_yield ([1, 2, 3]):    Print("yield:{}". Format (value) forValueinchGen_yield_from ([1, 2, 3]):    Print("yield from:{}". Format (value)
Result
Yield: [1, 2, 3]yieldfrom: 1yieldfrom: 2yieldfrom : 3

The yield from will establish a two-way channel between the caller and the child generator, that is, the yield from can accept a generator function, the caller can pass the data directly to the child generator via send, and the yield from can accept the data returned by the child generator

1 defGen_yield ():2     """3 Child Generators4 : return:5     """6Nums = []7i = 18      whileI < 4:9n =yieldITen         Print("Receive {}". Format (n)) Onei + = 1 A nums.append (n) -     returnNums -  the  - defGen_yield_from (): -val =yield  fromGen_yield () -     returnVal +  -  +Gen_value_list = [100, 200, 300] A #Calling Party atGen =Gen_yield_from () - #Send (None) activation generator - Print("yield return {}". Format (Gen.send (None))) -j =0 -  whileJ < 3: -     Try: in         Print("yield return {}". Format (gen.send (GEN_VALUE_LIST[J) )) -     exceptstopiteration as E: to         Print(e) +J + = 1
Gen activates the generator and sends the data via send, and the data is passed directly to the child generator Gen_yield
Execution results
yield return 1yieldreturn 2yieldreturn 3  [100, 200, 300]

Yield and yield from

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.