AsyncIO Flashcards

(16 cards)

1
Q

What AsyncIO is a coroutine function

A
  • A coroutine is a function that can be suspended and resumed.
  • A coroutine can be defined via the async def expression.
  • A subroutine (function) can be executed, starting at one point and finishing at another point. Whereas, a coroutine (async function) can be executed then suspended, and resumed many times before finally terminating.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is AsyncIO event loop

A

The asyncio event loop is a single-threaded scheduler that runs coroutine-based tasks by switching between them whenever their awaited I/O or timers become ready. It uses OS-level event notification (like epoll on linux) to drive cooperative concurrency.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Coroutine function vs coroutine object

A
  • You can think of a coroutine function as a factory for coroutine objects; more directly, remember that calling a coroutine function does not cause any user-written code to execute, but rather just builds and returns a coroutine object.
  • A coroutine Python object has methods, such as send() and close(). It is a type.
  • A coroutine object is an awaitable. This means it is a Python type that implements the await() method.
async def custom_coro():
    await asyncio.sleep(1)

coro = custom_coro()
print(type(coro))
# <class 'coroutine'>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Basic way to start new event loop for a program (that will execute main)

A
import asyncio

async def main():
    await custom_coro()

asyncio.run(main())
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Create event loop (low level method)

A

loop = asyncio.new_event_loop()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is Task

A
  • The asyncio event loop manages tasks. As such, all coroutines become and are managed as tasks within the event loop.
  • The create_task() function wraps an awaitable object into a higher-level Task object that’s scheduled to run concurrently on the event loop in the background. In contrast, awaiting a coroutine runs it immediately, pausing the execution of the caller until the awaited coroutine finishes.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How to create task for t coroutine, called "MyTask"

A
task = asyncio.create_task(task_coroutine(), name='MyTask')
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How to see if task was finished or cancelled?

A
task.done()
task.cancelled()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How to get results of a task and handle errors

A
try:
	# Get the return value from the wrapped coroutine
	value = task.result()
except asyncio.CancelledError:
	# Task was canceled
except asyncio.InvalidStateError:
	# Task is not yet done
except Exception:
	# Task failed and there is no result
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How to get list of all tasks

A

tasks = asyncio.all_tasks()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How to group awaitables to be treated as a single awaitable

A

results = await asyncio.gather(coro1(), asyncio.create_task(coro2()))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Wait for list of tasks to complete.
- All of them
- Only first
- First error

A
done, pending = await asyncio.wait(tasks, return_when=asyncio.ALL_COMPLETED) # default
first_done, rest = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
first_error, rest = await asyncio.wait(tasks, return_when=asyncio.FIRST_EXCEPTION)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Loop over async iterator (like async generator)

A
async for i in powers_of_two(5):
    g.append(i)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How to work with async resource with context manager (with)

A
        async with session.get(url) as response:
            print(f"{url}: status -> {response.status}")
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How to use async queue?
- Add elements
- Remove elements

A
queue = asyncio.Queue()

queue.put(user)
user = await queue.get()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How to sleep for 1 second (async)

A

asyncio.sleep(1)