"Python" "Control Flow" "Three" "co-process"

Source: Internet
Author: User
Tags generator

"""
# 16.2 The basic behavior of the generator using a co-process
#例子16-1 may be the simplest use of the association demo
Def simple_coroutine ():
Print ('--coroiutine started ')
x = Yield
Print ('--coroutine recived: ', x)
My_coro = Simple_coroutine ()
Print (My_coro) #<generator object Simple_coroutine at 0x10900f9e8>
#print (Next (My_coro))
‘‘‘
Coroiutine started
None
‘‘‘
#my_coro. Send (42)
‘‘‘
Coroutine recived:42
Stopiteration

‘‘‘
# The memo can be in one of four states. The current state can be determined using the inspect.getgeneratorstate () function, which returns one of the following strings.
#... ' gen_created ' waits to begin execution. The ' gen_running ' interpreter is executing ' gen_suspended ' pausing the ' gen_closed ' execution at the yield expression.
#... Because the parameters of the Send method are called the values of the paused yield expression, the Send method is called only when the coprocessor is in a paused state. However, if the process is not activated (that is, the state is ' gen_created '), the situation is different. Therefore, always call the next () activation coprocessor-or you can call My_coro.sen (None), as the effect
#... If you send a value other than none immediately after creating the co-process object, the following error will occur:
My_coro = Simple_coroutine ()
My_coro.send (1729) #TypeError: Can ' t send non-none value to a just-started generator

# example 16-2 outputs a two-value association
Def Simple_coro2 (a):
Print ('-started:a = ', a)
b = Yield A
Print ('-received:b = ', b)
c = Yield (a+b)
Print ('-received:c = ', c)
My_coro2 = Simple_coro2 (14)
From inspect import getgeneratorstate
Print (Getgeneratorstate (MY_CORO2)) #GEN_CREATED
Print (Next (MY_CORO2))
‘‘‘
-STARTED:A = 14
14

‘‘‘
Print (Getgeneratorstate (MY_CORO2)) #GEN_SUSPENDED
Print (My_coro2.send (28))
‘‘‘
-Started:b = 28
42
‘‘‘
Print (My_coro2.send (99))
‘‘‘
-RECEIVED:C = 99
Traceback (most recent):
File "/users/suren/pycharmprojects/fluentpython/kongzhiliucheng/xiecheng.py", line A, in <module>
My_coro2.send (99)
Stopiteration
‘‘‘
Print (Getgeneratorstate (MY_CORO2)) # ' gen_closed '


#例子16-31 calculation of the moving average
Def averager ():
Total = 0.0
Count = 0
Average = None
While True: #这个无限循环表明, as long as the caller constantly sends the value to the coprocessor, it will always receive the value and generate the result. This friend terminates only when the caller calls the. Close () method on the coprocessor or is not reclaimed by the garbage collector for the process reference.
term = yield average
Total + = term
Count + = 1
Average = Total/count
Coro_avg = Averager ()
Print (Next (coro_avg)) #None
Print (coro_avg.send) #10.0
Print (Coro_avg.send ()) #20.0
Print (Coro_avg.send (5)) #15.0


#16.4 Pre-excitation program decorator
From Functools Import Wraps

def coroutine (func):
@wraps (func)
def primer (*args,**kwargs):
Gen = func (*args,**kwargs)
Next (Gen)
Return Gen
Return Primer

@coroutine
Def averager ():
Total = 0.0
Count = 0
Average = None
While True:
term = yield average
Total + = term
Count + = 1
Average = Total/count

Coro_avg = Averager ()
From inspect import getgeneratorstate
Print (Getgeneratorstate (coro_avg)) #GEN_SUSPENDED
Print (coro_avg.send) #10.0
Print (Coro_avg.send ()) #20.0
Print (Coro_avg.send (5)) #15.0



#16.5 terminating the association and exception handling
#例子 16-7 Unhandled exception causes the coprocessor to terminate
From Functools Import Wraps
def coroutine (func):
@wraps (func)
def primer (*args,**kwargs):
Gen = func (*args,**kwargs)
Next (Gen)
Return Gen
Return Primer

@coroutine
Def averager ():
Total = 0.0
Count = 0
Average = None
While True:
term = yield average
Total + = term
Count + = 1
Average = Total/count
Coro_avg = Averager ()
Print (coro_avg.send) #40.0
Print (coro_avg.send) #45.0
Print (coro_avg.send (' spam ')) #TypeError: unsupported operand type (s) for + =: ' float ' and ' str '. At this point, the association terminates because the exception is not handled in the process. If you try to reactivate the process, it throws
Print (coro_avg.send) #不会处理


# example 16-8 handling exception code in the process
Class Demoexception (Exception):
"" The exception type defined for this presentation "
Def demo_exc_handling ():
Print ('--coroutine started ')
While True:
Try
x = Yield
Except demoexception:
Print (' * * * * demoexception handled. Continuing ... ')
else: #如果没有异常, the received value is displayed
Print ('->coroutine received:{!s} '. Format (x))
Raise RuntimeError (' This line should never run. ') #这一行永远不会执行, because only unhandled exceptions will terminate that infinite loop

#激活和关闭demo_exc_handling, no exception
Exc_coro = demo_exc_handling ()
Print (Next (Exc_coro)) #coroutine started
Print (Exc_coro.send (one)) #->coroutine received:11
Print (exc_coro.send) #->coroutine received:22
Exc_coro.close ()
From inspect import getgeneratorstate
Print (Getgeneratorstate (Exc_coro)) #GEN_CLOSED

#把DemoException异常传入demo_exc_handling不会导致协程中止
Exc_coro = demo_exc_handling ()
Print (Next (Exc_coro)) #-> Coroutine started
Print (Exc_coro.send (one)) #->coroutine received:11
Print (Exc_coro.throw (demoexception)) #*** Demoexception handled. Continuing ...
Print (Getgeneratorstate (Exc_coro)) #GEN_SUSPENDED

#如果无法处理传入的异常, the co-process will terminate.
Exc_coro = demo_exc_handling ()
Print (Next (Exc_coro)) #-> Coroutine started
Print (Exc_coro.send (11))
Print (Exc_coro.throw (zerodivisionerror))
‘‘‘
Traceback (most recent):
File "/users/suren/pycharmprojects/fluentpython/kongzhiliucheng/xiecheng.py", line 172, in <module>
Print (Exc_coro.throw (zerodivisionerror))
File "/users/suren/pycharmprojects/fluentpython/kongzhiliucheng/xiecheng.py", line 145, in demo_exc_handling
x = Yield
Zerodivisionerror
‘‘‘
Print (Getgeneratorstate (Exc_coro)) #GEN_CLOSED


#例子16-12 Use try/finally blocks to perform actions when the process terminates
Class Demoexception (Exception):
"" The exception type defined for this presentation "
Def demo_finally ():
Print ('--coroutine started ')
Try
While True:
Try
x = Yield
Except demoexception:
Print (' * * * * demoexception handled. Continuing ... ')
Else
Print ('--coroutine received:{!s} '. Format (x))
Finally
Print ('->coroutine ending ')

# Activate and deactivate demo_exc_handling, no exception
Exc_coro = demo_finally ()
Print (Next (Exc_coro)) #coroutine started after wrapping->coroutine ending
Print (Exc_coro.send (one)) #->coroutine received:11 printing after wrapping->coroutine ending
Print (exc_coro.send) #->coroutine received:22 printing after wrapping->coroutine ending
Exc_coro.close ()
From inspect import getgeneratorstate
Print (Getgeneratorstate (Exc_coro)) #GEN_CLOSED printing->coroutine after line break ending

# passing the demoexception exception into the demo_exc_handling will not cause the coprocessor to abort
Exc_coro = demo_finally ()
Print (Next (Exc_coro)) #-> Coroutine started after wrapping->coroutine ending
Print (Exc_coro.send (one)) #->coroutine received:11 printing after wrapping->coroutine ending
Print (Exc_coro.throw (demoexception)) #*** Demoexception handled. Continuing ... Print->coroutine after line break ending
Print (Getgeneratorstate (Exc_coro)) #GEN_SUSPENDED printing->coroutine after line break ending

#如果无法处理传入的异常, the co-process will terminate.
Exc_coro = demo_finally ()
Print (Next (Exc_coro)) #-> Coroutine started after wrapping->coroutine ending
Print (Exc_coro.send (11))
#print (Exc_coro.throw (Zerodivisionerror))
‘‘‘
Traceback (most recent):
File "/users/suren/pycharmprojects/fluentpython/kongzhiliucheng/xiecheng.py", line up, in <module>
Print (Exc_coro.throw (zerodivisionerror))
->coroutine ending
File "/users/suren/pycharmprojects/fluentpython/kongzhiliucheng/xiecheng.py", line 192, in demo_finally
x = Yield
Zerodivisionerror
->coroutine ending
‘‘‘
From inspect import getgeneratorstate
#print (Getgeneratorstate (Exc_coro)) #GEN_CLOSED print->coroutine after a line break ending



#让协程返回值
#例子16-14
From collections Import Namedtuple

result = namedtuple (' result ', ' Count average ')

Def averager ():
Total = 0.0
Count = 0
Average = None
While True:
term = yield
If term is None:
Break
Total + = term
Count + = 1
Average = Total/count
Return Result (Count,average)

Coro_avg = Averager ()
Print (Next (coro_avg)) #无产出
Print (coro_avg.send) #无产出
Print (Coro_avg.send ()) #无产出
Print (Coro_avg.send (6.5)) #无产出
#print (Coro_avg.send (None)) #StopIteration: Result (count=3, average=15.5)


#例子16-15
From collections Import Namedtuple
result = namedtuple (' result ', ' Count average ')

Def averager ():
Total = 0.0
Count = 0
Average = None
While True:
term = yield
If term is None:
Break
Total + = term
Count + = 1
Average = Total/count
Return Result (Count,average)




Coro_avg = Averager ()
Print (Next (coro_avg)) #无产出
Print (coro_avg.send) #无产出
Print (Coro_avg.send ()) #无产出
Print (Coro_avg.send (6.5)) #无产出
Try
Coro_avg.send (None)
Except stopiteration as exc:
result = Exc.value
Print (Result) #Result (count=3, average=15.5)

"""

























"Python" "Control Flow" "Three" "co-process"

Related Article

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.