Week 3 Assignment
Nitesh Dulal
Presidential Business School
PRG 400b: Advance Python Programming
Prof. Dr Aryan Thakur
May 19, 2023
Asyncio Callbacks
A Python package called Asyncio is employed for concurrent programming. Both multi-
processing and multi-threading are not it. Numerous Python asynchronous frameworks which
provide outstanding performance networking and internet servers, connections to databases
libraries, distributed task queues, etc. are built on the Asyncio basis (Lin, 2012). It's a co-routine-
based concurrency paradigm that offers beautiful constructions for writing concurrent Python
programming without the need of threads. Concurrent solutions are designed with an entirely
distinct philosophy than conventional thread-based solutions. We are aware that multiprocessing
in Python is useful for CPU-bound operations while threading is mostly employed for I/O-bound
processing. When creating concurrent applications, developers may utilize the async/await
syntax thanks to the Python asyncio standard library package. A Python program generally
executes functions for handling input values. Similarly, to this, asyncio requires the creation of
special functions known as co-routines. An ordinary function becomes a co-routine when the
async keyword is used.
Example of Code
Output
Explanation of Code
The above example shows the use of asyncio and callback function in python. In the
beginning we import asyncio module for writing the asynchronous code. Secondly, the main ()
function is introduced and it works as an entry point this program and then we recalled a callback
function named callback(result). The first argument is passed in this function which is named as
result. Likewise, we introduce function named coroutine(callback) function. This coroutines
functions helps to pause and resume, means it helps to welcome asynchronous behavior. In this
program we simulate an asynchronous operation using await asyncio.sleep(1). This delays the
output for 1 second. The result 100 is printed using callback(result) after the delay. The
asyncio.create_task(coroutine(callback)) creates a task that will run the coroutine
asynchronously. Lastly, the async event loop executes the program with the function named
asyncio.run(main ()).
Event Loops
Each and every asyncio application revolves around an event loop. Event loops carry out
network IO activities, operate subprocesses, and execute asynchronous tasks and callbacks. Only
must application developers require to make references to or access the loop object's methods;
instead, they ought to employ high-level asyncio operations like asyncio.run(). This section is
primarily for writers of lower-level programs, libraries, and frameworks that want greater
authority over the behavior of the event loop. Each asyncio application is centered around the
Python Event Loop. Organization of input and output tasks, do ad hoc assignments and
callbacks, perform circles, and execute subprocesses. When handling all the occurrences in a
computational function, the Python Event Loop is helpful. It moves around the path while the
program is running and keeps track of events as they approach and are carried out. For each
method, the Asyncio module allows a single event circle.
Example Code of Event Loop
Output
Explanation of code
The code is an example of event loop with the help of asyncio module in python. In the
beginning we import the asyncio module for supporting asynchronous code. The coroutine ()
function is introduced and it display the output indicating the coroutine has begun. It adds the
delay of 2 seconds. It displays the message of coroutine has completed. Next, we introduce the
function called primary () for serving the entry of our program. The coroutine function prints the
primary has been completed. We get the event using asyncio.get_event_loop(). It gives us access
to asyncio event loop. Utilizing loop, we execute the event loop all the way
through.run_until_complete(primary ()). Essentially initiates the primary () coroutine's
processing in an event loop and waits for it to finish. The message is displayed of primary
completed.
Asynchronous Programming
Asynchronous programming allows for the carrying out of numerous tasks at once
without awaiting the completion of others. Since asynchronous programming in Python
necessitates that the currently running coroutines collaborate and generate regulate on each other,
it is a case of cooperative multitasking [wiki]. If the current coroutine runs for a prolonged
period of time lacking calling await, execution will continue on that coroutine the entire time,
and all other coroutines in the thread will stay in a state of suspension. Compare this with the
proactive multitasking [wiki] of multithreaded and multiprocessor applications, whereby the OS
scheduler or Python interpreter chooses when switching among executing contexts, with the
moments at which changes might occur being generally challenging or even impossible to
anticipate.
Example Code of Asynchronous programming
Output
Explanation of code
The main () coroutine is executed inside the event loop named asyncio.run(main ()).
Afterwards, the main does three jobs. The function named asyncio.create_task() represents the
execution of greet() couroutine with various name of the games like cricket, basketball and
football. The event loop is started and every task involves greet () printing the favourite game
after 1 seconds asynchronously with await asyncio.sleep(1). When the task is waiting for
asynchronous sleep the event loop is fired. After every 1 second the task resumes and prints the
greeting message with game name. Finally, when the task is completed the await
asyncio.gather(*tasks) call returns the main() couroutine is completed. The loop then is
terminated.
References
Beazley, D. (2014). Python Gets an Event Loop (Again). Columns, 39(3), 38–41.
https://www.usenix.org/system/files/login/articles/09_beazley.pdf
Lee, K. D. (2010). Python Programming Fundamentals (1st ed.). Springer.
https://doi.org/10.1007/978-1-84996-537-8_6
Lin, J. W.-B. (2012). WHY PYTHON IS THE NEXT WAVE IN EARTH SCIENCES
COMPUTING. Bulletin of the American Meteorological Society, 93(12), 1823–
1824. http://www.jstor.org/stable/26219361
Lukkarinen, A., Malmi, L., & Haaranen, L. (2021). Event-driven Programming in Programming
Education. ACM Transactions on Computing Education, 21(1), 1–31.
https://doi.org/10.1145/3423956