Skip to content

Instantly share code, notes, and snippets.

View jorenham's full-sized avatar

Joren Hammudoglu jorenham

  • Delft, the Netherlands
View GitHub Profile
@jorenham
jorenham / counting_using_generics.py
Created March 22, 2024 02:04
Emulating integer in Python's type system: addition and subtraction
from __future__ import annotations
from typing import Protocol
class _Int(Protocol):
def __int__(self) -> int: ...
def __pos__(self) -> _Int: ...
def __neg__(self) -> _Int: ...
@jorenham
jorenham / asyncio_eventloop_benchmark.py
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
jorenham / example.py
Last active March 29, 2022 14:25
`@main` decorator as alternative to `if __name__ == '__main__': ...`
import asyncio
from run import main
@main(debug=True)
async def __amain__():
await asyncio.sleep(0.1)
fp = open(__file__)
@jorenham
jorenham / async_init.py
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
jorenham / pause_django_caching.py
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
@contextlib.contextmanager
def disable_caches(*aliases: str) -> ContextManager[tuple[str, ...]]:
"""Temporarily disable django caching backends. By default, all connected
@jorenham
jorenham / cmp.py
Last active October 18, 2021 13:02
Python cmp function, type annotated, and correctly handled nan's
from typing import Optional, TYPE_CHECKING
if 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
jorenham / generic_type_pattern_matching.py
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
jorenham / demo.py
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
jorenham / asyncio_shield_misleading.py
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
jorenham / traits.py
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__')