Skip to content

quick python

Roberto Fronteddu edited this page May 18, 2026 · 18 revisions

Map

Map for each

for k, v in x_map.items():
    ...

To access elements in order ...python for k, v in sorted(x_map.items()):


Get or default
```python
x_map.get(k, -1)

Given a map/dictionary whose values are lists, get all items in the list for key k starting at index start.

m = []
for index in range (start, len(log[k])):
    m.append(log[k][index])

OR

m = log[k][start:]

Creates boilerplate for map

from collections import defaultdict
x = defaultdict[set]

Asyncio

List of RPCs:

import asyncio
...
r_calls = []
r_calls.append(f) # f is an async def function
...
results = await asyncio.gather(*r_calls)

A loop that waits asynchronously

async def ticker():
    while True:
        print("tick")
        await asyncio.sleep(1)

async def main():
    await ticker()

asyncio.run(main())

Run multiple workers

import asyncio

async def worker(name):
    while True:
        print(f"{name} working")
        await asyncio.sleep(1)

async def main():
    await asyncio.gather(
        worker("A"),
        worker("B"),
        worker("C"),
    )

asyncio.run(main())

Blocking to concurrent:

tasks = [asyncio.create_task(fetch(url)) for url in urls]
results = await asyncio.gather(*tasks)

Blocking to asyncio

import asyncio
import time

def blocking_work():
    time.sleep(2)
    return "done"

async def main():
    result = await asyncio.to_thread(blocking_work)
    print(result)

asyncio.run(main())

Producer Consumer

import asyncio

async def producer(queue):
    for i in range(5):
        await queue.put(i)
        print("produced", i)
    await queue.put(None)  # sentinel

async def consumer(queue):
    while True:
        item = await queue.get()
        if item is None:
            break
        print("consumed", item)
        queue.task_done()

async def main():
    queue = asyncio.Queue()

    await asyncio.gather(
        producer(queue),
        consumer(queue),
    )

asyncio.run(main())

Prevent interleaving:

lock = asyncio.Lock()
counter = 0

async def increment():
    global counter

    async with lock:
        old = counter
        await asyncio.sleep(0)  # simulate yield
        counter = old + 1

Practical template

import asyncio

async def handle_item(item):
    print("start", item)
    await asyncio.sleep(1)
    print("done", item)
    return item * 2

async def main():
    items = [1, 2, 3, 4, 5]

    tasks = [
        asyncio.create_task(handle_item(item))
        for item in items
    ]

    results = await asyncio.gather(*tasks)
    print(results)

if __name__ == "__main__":
    asyncio.run(main())

Practical template 2:

async def handle_message(msg):
    ...

async def receive_loop():
    while True:
        msg = await read_message()
        asyncio.create_task(handle_message(msg))

Clone this wiki locally