Skip to content

Instantly share code, notes, and snippets.

View alkasm's full-sized avatar

Alexander Reynolds alkasm

View GitHub Profile
@alkasm
alkasm / dataclass_required_field.py
Created July 24, 2022 02:24
A pattern for "required" arguments in dataclasses, allowing for fields without defaults to follow fields with defaults.
from dataclasses import dataclass, field
from datetime import datetime
from typing import Optional, TypeVar
T = TypeVar("T")
def required() -> T:
f: T
@alkasm
alkasm / events.py
Created February 6, 2021 10:37
Cooperative, event-driven, producer/consumer patterns
from collections import deque
import logging
import signal
from threading import Condition, Event, Thread
import time
logging.basicConfig(level=logging.INFO)
class Stop(Exception):
@alkasm
alkasm / metaattrs.py
Created December 7, 2020 21:33
Metaclass to add class attrs
class Meta1(type):
@classmethod
def __prepare__(cls, *args):
return {"decorator": lambda f: f, "prepared_attr": "prepared_attr_value"}
class Meta2(type):
def __new__(cls, name, bases, namespace):
namespace["decorator"] = lambda f: f
namespace["new_attr"] = "new_attr_value"
from concurrent.futures import ThreadPoolExecutor, TimeoutError
class TimeoutIterable:
"""Iterable that exhausts if it takes longer than `timeout` seconds to obtain the next value."""
def __init__(self, iterable, timeout=None):
self._it = iter(iterable)
self.timeout = timeout
# Level 0
{"asdf": {"a": [1, 2, 3], "b": 500}, "qwerty": {"a": [4, 5, 6], "b": 1000}}
# Level 1
{
"asdf": {"a": [1, 2, 3], "b": 500},
"qwerty": {"a": [4, 5, 6], "b": 1000}
}
# Level 2
@alkasm
alkasm / timer.py
Last active July 29, 2019 23:17 — forked from bradmontgomery/LICENSE.txt
A python decorator that logs execution time.
from functools import wraps
import logging
import time
logger = logging.getLogger(__name__)
def timed(func):
"""This decoratorlogs the execution time for the decorated function."""