Skip to content

Instantly share code, notes, and snippets.

@internetimagery
internetimagery / underscore.py
Last active Jun 15, 2021
Experiment in "underscore" placeholder lambda generation. Detecting when to finalize and when to build.
View underscore.py
"""
Yet another placeholder underscore lambda replacement.
This is a proof of concept trying to tackle the difficult issue of detecting when the function is still being built, and when it is being used.
>>> list(map(_.upper(), "abc"))
>>> # ["A", "B", "C"]
"""
import operator
import sys
from dis import disco, opmap
@internetimagery
internetimagery / class_decorator.py
Created May 29, 2021
Note: Example of bound class decorator
View class_decorator.py
# 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
Testing tee efficiency against list
View tee_test.py
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 Jun 3, 2021
Run async code in sync (helpful for piecemeal conversion to async within codebase)
View run_sync.py
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
Global Cache. Manage cache through proxies. Invalidate data via tags, and automatically invalidate dependencies.
View cache.py
import time
import heapq
import types
import itertools
import functools
import threading
import contextlib
import collections
import operator
@internetimagery
internetimagery / defer.py
Created Apr 27, 2021
Callback experiment (async alternative)
View defer.py
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 Apr 10, 2021
Traceback Generation
View traceback_gen.py
# 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__",), (),
View lockfile.py
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
Context manager for your context managers
View manager.py
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 Apr 26, 2020
Transmutation Framework (provide tiny functions to convert a to b, and let the framework chain them together to convert anything to anything)
View transmute.py
# 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