Skip to content

Instantly share code, notes, and snippets.

@internetimagery
internetimagery / class_decorator.py
Created May 29, 2021 01:17
Note: Example of bound class decorator
# If making a class decorator. A MethodType is required to make it bind to methods correctly, and pass "self" argument across.
import types
class Decorator(object):
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
return self.func(*args, **kwargs)
def __get__(self, inst, _=None):
if inst:
@internetimagery
internetimagery / tee_test.py
Created May 25, 2021 09:00
Testing tee efficiency against list
from itertools import tee
from time import time
def t1(count):
l = []
for i in range(count):
l.append(i)
def t2(count):
a, b = tee(range(count))
@internetimagery
internetimagery / run_sync.py
Last active June 3, 2021 01:47
Run async code in sync (helpful for piecemeal conversion to async within codebase)
from concurrent.futures import ThreadPoolExecutor
import asyncio
def run_sync(task):
try:
loop = asyncio.get_event_loop()
except RuntimeError:
loop = None
if not loop or loop.is_running():
@internetimagery
internetimagery / cache.py
Last active May 30, 2021 10:01
Global Cache. Manage cache through proxies. Invalidate data via tags, and automatically invalidate dependencies.
import time
import heapq
import types
import itertools
import functools
import threading
import contextlib
import collections
import operator
@internetimagery
internetimagery / defer.py
Created April 27, 2021 19:48
Callback experiment (async alternative)
from concurrent.futures import ThreadPoolExecutor
_pool = ThreadPoolExecutor()
def defer(caller, *args, **kwargs):
def decorator(func):
global _pool
future = _pool.submit(caller, *args, **kwargs)
future.add_done_callback(lambda f: func(f.result()))
@internetimagery
internetimagery / traceback_gen.py
Last active April 10, 2021 12:33
Traceback Generation
# Generate tracebacks from arbitrary information
import types, sys
def create_traceback(stack, _code=compile("__temp__()", "", "exec").co_code):
""" Create a traceback from given information, or None if provided stack is empty. """
func = None
for frame in stack:
func = types.FunctionType(
types.CodeType(
0, 0, 0, 0, 1, 64, _code, (None,), ("__temp__",), (),
@internetimagery
internetimagery / lockfile.py
Last active May 26, 2020 11:09
Simple lockfile
from __future__ import print_function
import os
import time
import errno
import socket
class FileLock(object):
CONTENTS = "Locked by\n * host: {}\n * process: {}".format(
@internetimagery
internetimagery / manager.py
Last active May 2, 2020 00:07
Context manager for your context managers
import sys
import contextlib
@contextlib.contextmanager
def context_manager_manager(*managers):
for manager in managers:
manager.__enter__()
err = (None, None, None)
try:
@internetimagery
internetimagery / transmute.py
Last active April 26, 2020 23:15
Transmutation Framework (provide tiny functions to convert a to b, and let the framework chain them together to convert anything to anything)
# Copyright 2020 Jason Dixon
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
@internetimagery
internetimagery / execution_path.py
Created January 30, 2020 10:19
Follow execution path around. Carry scope along with objects.
from contextlib import contextmanager
from threading import current_thread
from collections import defaultdict
class Scope(object):
_scope = defaultdict(list)
_tagged = {}