Skip to content

Instantly share code, notes, and snippets.

@normanlmfung
normanlmfung / gist:95bacafd214a26b3af85c6bd02c6c329
Created March 30, 2024 23:11
python_syntax_asyncio_create_task_fireforget
import asyncio
from datetime import datetime
def _log(msg : str):
print(f"{datetime.utcnow()} {msg}")
async def dummy(name, delay_sec):
_log(f"{name} entering ...")
await asyncio.sleep(delay_sec)
_log(f"{name} done for the day!")
@normanlmfung
normanlmfung / gist:3b24eea6735ee4c2f7c4ac623b91f256
Created March 30, 2024 23:09
python_syntax_asyncio_create_task
import asyncio
async def greet(name):
await asyncio.sleep(1)
print(f"Hello, {name}!")
async def main():
task1 = asyncio.create_task(greet("Alice"))
task2 = asyncio.create_task(greet("Bob"))
await asyncio.gather(task1, task2)
@normanlmfung
normanlmfung / gist:a5f85dcf0c6a12ca8a7599d92ce3d9a7
Created March 30, 2024 23:07
python_syntax_asyncio_run_in_executor
import asyncio
import concurrent.futures
def sync_function():
return "Hello from a synchronous function!"
async def main():
with concurrent.futures.ThreadPoolExecutor() as executor:
result = await asyncio.get_running_loop().run_in_executor(executor, sync_function)
print(result)
@normanlmfung
normanlmfung / gist:14fc54b5c2dcfbf92f2f2d0b90ed002f
Created March 30, 2024 23:04
python_syntax_asyncio_get_event_loop
import asyncio
async def my_coroutine():
print("Hello,")
await asyncio.sleep(1)
print("world!")
def main():
loop = asyncio.get_event_loop()
try:
from functools import reduce
numbers = [1, 2, 3, 4, 5]
sum_result = reduce(lambda x, y: x + y, numbers)
print("Sum of the numbers:", sum_result)
nums = [ 1,2,3,4,5 ]
squares = []
for num in nums:
squares.append(num**2)
# instead of loop, use 'map'
squares = list(map(lambda num: num ** 2, nums))
@normanlmfung
normanlmfung / gist:d098763369a9241d34d731cc6c3e6333
Created March 30, 2024 22:42
python_syntax_three_semaphore
'''
https://superfastpython.com/asyncio-semaphore/
https://superfastpython.com/thread-semaphore/
https://superfastpython.com/multiprocessing-semaphore-in-python/
There're three versions of Semaphore:
from asyncio import Semaphore
from threading import Semaphore
from multiprocessing import Semaphore
@normanlmfung
normanlmfung / gist:539de6aac65d00911f363b5fc847afd7
Created March 30, 2024 22:39
python_syntax_concurrent_futures_ThreadPoolExecutor_task_chaining
import concurrent.futures
import time
def background_task1():
item_list = []
for i in range(10):
item_list.append(i)
time.sleep(1)
# Simulate an exception being thrown
@normanlmfung
normanlmfung / gist:fc246d2afde6cdc12230a8610b45c590
Last active June 10, 2024 02:07
python_syntax_concurrent_futures_ThreadPoolExecutor
import concurrent.futures
import time
def background_task(task_id):
item_list = []
for i in range(3):
item_list.append((task_id, i))
time.sleep(1)
return item_list
# This is taken DIRECTLY from Geekforgeeks https://www.geeksforgeeks.org/heap-queue-or-heapq-in-python/
import heapq
li = [5, 7, 9, 1, 3]
# If you call heapify, when you call heappop, order 1,3,5,7,8. If you comment out heapify call, heappop oder 5,7,9,1,3
heapq.heapify(li)
while li:
print(heapq.heappop(li))
# Example 2 with tuples: (w, n) where w = weight, n = node id. Heapify uses 'w' to sort first, then 'n' as tie-breaker if there are two/more elements with same 'w'.