Skip to content

Instantly share code, notes, and snippets.

# https://docs.python.org/3/library/contextlib.html
from contextlib import contextmanager
class MessageWriter(object):
def __init__(self, filename):
self.file_name = filename
@contextmanager
def open_file(self):
try:
# Taken DIRECTLY from William's article https://realpython.com/python-interface/
import abc
class FormalParserInterface(metaclass=abc.ABCMeta):
@classmethod
def __subclasshook__(cls, subclass):
print("FormalParserInterface.__subclasshook__")
return (hasattr(subclass, 'load_data_source') and
callable(subclass.load_data_source) and
hasattr(subclass, 'extract_text') and
@normanlmfung
normanlmfung / gist:1665931c2eb94f2e02756a0dfd0f849a
Created March 30, 2024 22:30
python_syntax_decorator_timer
# timer (Simply log the duration of time the wrapped method took). Can also be extended to filter/modify parameters.
def timer(method):
def timed(*args, **kw):
start = time.time()
result = method(*args, **kw)
elapsed = (time.time() - start) * 1000
logger.info(f'@timer {method.__qualname__} returned in {elapsed} ms. {args_}')
return result
@normanlmfung
normanlmfung / gist:a44a2797624c6f59e1c626fdbe060504
Created March 30, 2024 22:31
python_syntax_decorator_apiguard
# REST API guard: check api key (If incorrect API key, raise exception)
def check_api_key(api_key : str, request : Any, symmetric_key : str, kms_gizmo : Any):
def decorator(method):
headers = request.headers
encrypted_api_key_from_header = headers.get("X-Api-Key")
decrypted_api_key_from_header = encrypted_api_key_from_header
if kms_gizmo:
decrypted_api_key_from_header = kms_gizmo.decrypt(decrypted_api_key_from_header)
if symmetric_key:
decrypted_api_key_from_header = cipher_gizmo.decrypt(encrypted_text=decrypted_api_key_from_header, key=symmetric_key)
from collections import defaultdict
word_lists = defaultdict(list)
pairs = [('a', 1), ('b', 2), ('c', 3), ('a', 4), ('b', 5)]
for key, value in pairs:
word_lists[key].append(value) # Append value to list
print(word_lists.get('d', []))
# 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'.
@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
@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: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
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))