Skip to content

Instantly share code, notes, and snippets.


Joren jorenham

View GitHub Profile
jorenham /
Last active August 29, 2022 23:38
Directly measures the asyncio event loop iteration speed, and compares it with a sync for-loop
import asyncio
import time
from time import perf_counter_ns
# noinspection PyPep8Naming
class ns_per_it:
__slots__ = 'n', 'res'
def __init__(self, n: int):
jorenham /
Last active March 29, 2022 14:25
`@main` decorator as alternative to `if __name__ == '__main__': ...`
import asyncio
from run import main
async def __amain__():
await asyncio.sleep(0.1)
fp = open(__file__)
jorenham /
Created November 4, 2021 16:43
async version of __init__
import asyncio
class AsyncInit:
def __await__(self):
async def _():
await self.__ainit__()
return self
return _().__await__()
jorenham /
Last active October 22, 2021 15:29
Temporarily disable django caching
import contextlib
from typing import ContextManager
from django.core import cache
from django.core.cache.backends.dummy import DummyCache
def disable_caches(*aliases: str) -> ContextManager[tuple[str, ...]]:
"""Temporarily disable django caching backends. By default, all connected
jorenham /
Last active October 18, 2021 13:02
Python cmp function, type annotated, and correctly handled nan's
from typing import Optional, TYPE_CHECKING
from _typeshed import SupportsLessThan
def cmp(a: 'SupportsLessThan', b: 'SupportsLessThan') -> Optional[int]:
"""Return 1 if a > b, 0 if a == b, -1 if a < b, otherwise None.
>>> cmp(42, 69), cmp(666, 666), cmp(69, 42), cmp(0, float('nan'))
jorenham /
Created October 17, 2021 12:20
Generic type argument matching on builtin collections using slicing syntax
class FancyGeneric:
def __class_getitem__(cls, params):
if not isinstance(params, tuple):
params = (params,)
newparams = []
for param in params:
if isinstance(param, slice):
assert param.start is None and param.step is None
jorenham /
Last active July 26, 2021 13:35
Increment a float with the smallest possible value
import sys
for x in (0.0, 1/10, -1/10, sys.float_info.max, sys.float_info.min, float('inf'), float('-inf'), float('NaN')):
print(f'{x}++ => {float_incr(x)}')
i, xi = 0, float('-inf')
while xi < float('inf'):
x = float_incr(xi)
assert x > xi
xi = x / 2 if x < 0 else x * 2
jorenham /
Created February 9, 2021 13:06
demonstration of why asyncio.shield is misleading
import asyncio
async def task():
print('task start')
await asyncio.sleep(.5)
print('task done')
async def run_tasks():
jorenham /
Created December 21, 2020 03:40
Ridiculous syntax for class creation with extra parameters in pure python
This is valid (but ridiculous) syntax:
spam_with_eggs = Spam<<'eggs'>>('ham', 'bacon')
class _TraitAlias:
__slots__ = ('__origin__', '__traits__')
jorenham /
Last active September 28, 2019 22:34
Best exception handling in Python
import webbrowser
def main():
return 42/0
if __name__== '__main__':