Facebook Twitter Instagram
    Facebook Twitter Instagram Pinterest Vimeo
    Hand On CodeHand On Code
    Hand On CodeHand On Code
    Home»python»Coroutine in Python
    python

    Coroutine in Python

    April 7, 2023No Comments6 Mins Read
    Share
    Facebook Twitter LinkedIn Pinterest Email

    Python’s coroutine system Read, Discuss, and Engage in Instructional Videos.

    Prerequisite: Generators Everyone is conversant with the term “function,” which may also be referred to as a subroutine, procedure, or sub-process, amongst other names. A function is a group of related instructions that are packaged together to carry out a certain operation. Helper functions or subroutines are functions that are used when the logic of a complicated function is broken down into numerous self-contained steps that are also functions. Subroutines are a subset of helper functions.

    Python’s main function is the one in charge of coordinating how its subroutines are used, and it is the main function that is responsible for calling Python’s subroutines. The number of entries in a subroutine is one.

    point.

    Coroutine in Python

    The term “coroutine” refers to a generalization of the term “subroutine.” They are used for cooperative multitasking, which is a form of multitasking in which a process will voluntarily relinquish (give away) control to another process at regular intervals or when it is inactive. This allows numerous applications to be run at the same time. The distinction between a coroutine and a subroutine consists on the following:

    :

    • Unlike subroutines, coroutines have many entry points for suspending and resuming execution. Coroutine can suspend its execution and transfer control to other coroutine and can resume again execution from the point it left off.
    • Unlike subroutines, there is no main function to call coroutines in a particular order and coordinate the results. Coroutines are cooperative that means they link together to form a pipeline. One coroutine may consume input data and send it to other that process it. Finally, there may be a coroutine to display the result.

    Coroutine in Python The Difference Between Thread and Coroutine

    Since threads and coroutines appear to perform the same function, you might be wondering how the former differs from the latter. When it comes to threads, the operating system (or run time environment) is the component that is responsible for switching between threads in accordance with the scheduler. While in the case of a coroutine, the decision of when to switch between coroutines is made by the programmer in conjunction with the programming language. Coroutines are a form of cooperative multitasking that operate by pausing and restarting at predetermined places in the program. Python’s built-in coroutine

    Coroutines are a type of generator that are used in Python. They are quite similar to generators, but they include a few extra methods and a slightly different way of using yield statements. While coroutines are primarily responsible for data consumption, generators are responsible for producing iteration data. Since Python 2.5, the yield statement has been given a little tweak; now, in addition to being used as a statement, yield can also be used as an expression. For instance, on the right side of the assignment, you would write…

    –

    line = (yield)

    whatever value we pass to the coroutine is captured by the (yield) expression, and it then returns that value.

    Through the use of the send() method, a value may be transmitted to the coroutine. Consider, for instance, this coroutine that prints out the name with the prefix “Dear” included in it. We will send the names to the queue using the send command.()

    method.

    • Python3

    Python3


    # Python3 program for demonstrating

    # coroutine execution

    def


    print_name(prefix):



    print


    (


    "Searching prefix:{}"


    .


    format


    (prefix))



    while


    True


    :



    name


    =


    (


    yield


    )



    if


    prefix


    in


    name:



    print


    (name)

    # calling coroutine, nothing will happen

    corou


    =


    print_name(


    "Dear"


    )

    # This will start execution of coroutine and

    # Prints first line "Searching prefix..."

    # and advance execution to the first yield expression

    corou.__next__()

    # sending inputs

    corou.send(


    "Atul"


    )

    corou.send(


    "Dear Atul"


    )

    Output:

    Searching prefix:Dear
    Dear Atul

    The Carriage Out of the Routine

    The execution of the coroutine is very much like the generator in this regard. When we call the coroutine method, nothing happens; the only time it executes is in response to the next() and sends () methods. This can be seen quite clearly in the example that was just presented, as the execution of our coroutine does not begin until after the __next__() method has been called. Following this call, the execution will proceed to the first yield expression. At this point, the execution will pause as it awaits the value to be sent to the corou object. It performs a check for a prefix whenever the very first value is provided to it, and it only prints the name if a prefix is present. After it has finished printing the name, it will continue to iterate through the loop until it comes across the equation name = yield once more. When a Coroutine Is Finished

    It is possible for a coroutine to run indefinitely; the close() method is what is utilized to terminate a coroutine. The closing of a coroutine causes the generation of a GeneratorExit exception, which can be captured in the customary fashion for exceptions. If, after the coroutine has been closed, we make an attempt to communicate values, we will be met with the StopIteration exception. Here is a straightforward illustration:

    :

    • Python3

    Python3


    # Python3 program for demonstrating

    # closing a coroutine

    def


    print_name(prefix):



    print


    (


    "Searching prefix:{}"


    .


    format


    (prefix))



    try


    :



    while


    True


    :



    name


    =


    (


    yield


    )



    if


    prefix


    in


    name:



    print


    (name)



    except


    GeneratorExit:



    print


    (


    "Closing coroutine!!"


    )

    corou


    =


    print_name(


    "Dear"


    )

    corou.__next__()

    corou.send(


    "Atul"


    )

    corou.send(


    "Dear Atul"


    )

    corou.close()

    Output:

    Searching prefix:Dear
    Dear Atul
    Closing coroutine!!

    Creating a pipeline through the use of chained coroutines

    Pipes can be set up with the help of coroutines. across the use of the send() method, we are able to chain together many coroutines and send data across the pipe. A pipe needs

    :

    • An

      initial source

      (producer) derives the whole pipeline. The producer is usually not a coroutine, it’s just a simple method.
    • A

      sink

      , which is the endpoint of the pipe. A sink might collect all data and display it.

    Coroutine in Python

    The following is a straightforward illustration of chaining.

    –

    Coroutine in Python

    • Python3

    Python3


    # Python3 program for demonstrating

    # coroutine chaining

    def


    producer(sentence, next_coroutine):



    '''



    Producer which just split strings and



    feed it to pattern_filter coroutine



    '''



    tokens


    =


    sentence.split(


    " "


    )



    for


    token


    in


    tokens:



    next_coroutine.send(token)



    next_coroutine.close()

    def


    pattern_filter(pattern


    =


    "ing"


    , next_coroutine


    =


    None


    ):



    '''



    Search for pattern in received token



    and if pattern got matched, send it to



    print_token() coroutine for printing



    '''



    print


    (


    "Searching for {}"


    .


    format


    (pattern))



    try


    :



    while


    True


    :



    token


    =


    (


    yield


    )



    if


    pattern


    in


    token:



    next_coroutine.send(token)



    except


    GeneratorExit:



    print


    (


    "Done with filtering!!"


    )

    def


    print_token():



    '''



    Act as a sink, simply print the



    received tokens



    '''



    print


    (


    "I'm sink, i'll print tokens"


    )



    try


    :



    while


    True


    :



    token


    =


    (


    yield


    )



    print


    (token)



    except


    GeneratorExit:



    print


    (


    "Done with printing!"


    )

    pt


    =


    print_token()

    pt.__next__()

    pf


    =


    pattern_filter(next_coroutine


    =


    pt)

    pf.__next__()

    sentence


    =


    "Bob is running behind a fast moving car"

    producer(sentence, pf)

    Output:

    I'm sink, i'll print tokens
    Searching for ing
    running
    moving
    Done with filtering!!
    Done with printing!

    Citations and Bibliographies


    • http://www.dabeaz.com/coroutines/Coroutines.pdf

    • https://en.wikipedia.org/wiki/Coroutine
    Coroutine in Python Learn Python free Python Code Python Course Free download python coursefree Courses Download Python Language
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleIntroduction to Git and GitHub for Python Developers
    Next Article Python Program to Count the Number of Matching Characters in a Pair of String

    Related Posts

    python

    Class method vs Static method in Python

    April 7, 2023
    python

    Python Program to Count the Number of Matching Characters in a Pair of String

    April 7, 2023
    python

    Introduction to Git and GitHub for Python Developers

    April 7, 2023
    Add A Comment

    Leave A Reply Cancel Reply

    Facebook Twitter Instagram Pinterest
    © 2023 ThemeSphere. Designed by ThemeSphere.

    Type above and press Enter to search. Press Esc to cancel.