Course Content

Coroutines In Python | Python Tutorials For Absolute Beginners In Hindi #77

In this course, we are working on PyCharm IDE. There are also many other options available like Spyder, Idle, Wing, etc. but we will go with PyCharm for this series, and you will see its benefits in the upcoming tutorials. If you haven't downloaded it yet, then download it by clicking on the Download PyCharm. This will take you to the PyCharm official site. For installation guidelines, check Downloading Python and PyCharm Installation tutorial.

 

 

I will recommend you installing the community version as the other one will expire after a month trial, and after that, you have to pay to use its features.

Moving forward, let's just open our PyCharm and create a new file.

 

 

As always, I am again going to repeat: not to name our file similar to a module name. The reason for that, I have discussed in Tutorial #45. You can give it a read or watch the video for further clarification.

 

 

We are going to name our file cour.py here.

Our today's topic for this course is Coroutines. Before learning the concept of coroutines, we must have some brief knowledge or understanding related to generators. A generator is a function that produces a sequence of results instead of returning a value. You generate a series of values (using the yield statement). If you are not familiar with the working and concept of generators, then you must visit the Generators in Python Tutorial of this course, i.e. Tutorial #72. Both generator and coroutine operate over the data; the main differences are:

  •      Generators produce data
  •      Coroutines consume data

Coroutines:-

Coroutines are mostly used in cases of time-consuming programs, such as tasks related to machine learning or deep learning algorithms or in cases where the program has to read a file containing a large number of data. In such situations, we do not want the program to read the file or data, again and again, so we use coroutines to make the program more efficient and faster. Coroutines run endlessly in a program because they use a while loop with a true or 1 condition so it may run until infinite time. Even after yielding the value to the caller, it still awaits further instruction or calls. We have to stop the execution of coroutine by calling coroutine.close() function. It is very crucial to close a coroutine because its continuous running can take up memory space as we have discussed in Tutorial #75, related to function caching. We can define a coroutine using the following statements.

def myfunc():
    while True:
        value = (yield)

The while block continues the execution of the coroutine for as long as it receives values. The value is collected through the yield statement.

Coroutine Execution:- 

Execution is the same as of a generator. When you call a coroutine, nothing happens. They only run in response to the next() and send() methods. Coroutine requires the use of the next statement first so it may start its execution. Without a next() it will not start executing. We can search a coroutine by sending it the keywords as input using object name along with send(). The keywords to be searched are send inside the parenthesis. 

When we run the next() function the first time, the coroutine executes and waits for new input. After the input is sent to it using the send() function, it executes it and again waits for next input, and the process goes on like this because we have set the while loop as true, so it will never exit its execution. In order to make the execution stop, we have to close the coroutine using coroutine.close() function.

  • send() — used to send data to coroutine
  •  close() — to close the coroutine

Example:

def myfunc():
    print("Code With Harry")
    while True:
        value = (yield)
        print(value)

coroutine =myfunc()
next(coroutine)
coroutine.send("Python")
coroutine.send(" Tutorial ")
coroutine.close()

Output:-

Code With Harry
 Python 
 Tutorial

After closing coroutine, if we send values, it will raise StopIteration exception. Coroutines are used for data processing mechanisms. Coroutines are similar to generators, except they wait for information to be sent to it using send() function.

Code as described/written in the video


def searcher():
    import time
    # Some 4 seconds time consuming task
    book = "This is a book on harry and code with harry and good"
    time.sleep(4)

    while True:
        text = (yield)
        if text in book:
            print("Your text is in the book")
        else:
            print("Text is not in the book")

search = searcher()
print("search started")
next(search)
print("Next method run")
search.send("harry")

search.close()
search.send("harry")
# input("press any key")
# search.send("harry and")
# input("press any key")
# search.send("thi si")
# input("press any key")
# search.send("joker")
# input("press any key")
# search.send("like this video")

Comments(2)

Prafullep 7 months, 3 weeks ago
Sorry nahi samajh me aaya
Ansh_Shrivas 2 months, 2 weeks ago
My function in not working
def file():
    with open('Docs.txt','a+') as f:
        inp=input('Enter text in file : ')
        f.write(f'{inp}')

def searcher():
    with open('Docs.txt') as f:
        while True:
            text = (yield)
            if text in f:
                print("Your text is in the book")
            else:
                print("Text is not in the book")

file()
search = searcher()
print("search started")
next(search)
print("Next method run")
search.send("in this")
search.close()

# input("press any key")
# search.send("harry and")
# input("press any key")
# search.send("thi si")
# input("press any key")
# search.send("joker")
# input("press any key")
# search.send("like this video")

Resources

No downloadable resources for this video. If you think you need anything, please post it in the QnA!

Course Announcements

Any Course related announcements will be posted here