Skip to content

Instantly share code, notes, and snippets.

View kurtbrose's full-sized avatar
💭
carbon based

Kurt Rose kurtbrose

💭
carbon based
View GitHub Profile
@kurtbrose
kurtbrose / no_overlap_ids.py
Last active January 11, 2024 22:34
Helper to reset the sequences on a postgres database before running CI to ensure that ids will be very different between tables.
from sqlalchemy import select, text
def reset_sequences(engine, schema="public", gap=10000):
"""
Reset all sequences in a given schema to 10000, 20000, etc. so that ids won't overlap easily.
Ensures we don't get "lucky" and crossing ids between tables works because they are both id=1,
passing a test that should fail.
"""
with engine.connect() as conn:
@kurtbrose
kurtbrose / param_match.py
Last active August 16, 2023 23:03
Function parameter matching type guard.
"""
This defines a decorator that works kind of like a type-guard (https://peps.python.org/pep-0647/) for the arguments
of a function.
The usefulness of this is for functions that "defer" their arguments to another function, e.g. places where you
would call functools.wraps().
@same_params_as(f)
@functools.wraps(f)
def passes_args_through(*a, **kw):
@kurtbrose
kurtbrose / graphlate.js
Last active July 22, 2023 21:36
graphlate -- json adjacent graph inflation / deflation to references
function deflate(obj) {
function _deflate(obj, _sofar = new Map(), _cur_ref = [0]) {
if (obj === null || typeof obj !== 'object') {
return obj;
}
if (Array.isArray(obj)) {
return obj.map(v => _deflate(v, _sofar, _cur_ref));
}
@kurtbrose
kurtbrose / import_all.py
Created April 10, 2023 21:18
Helper to recursively import all .py files on disk. This ensures that all side effects from importing a module "trigger". (For example, registering a model with the ORM, or adding routes.) Call it with the name of a top-level module within the directory.
import re
import importlib
from pathlib import Path
def import_all(module_name: str, ignore: str = None) -> None:
"""
Helper to recursively import all .py files on disk.
This ensures that all side effects from importing a module "trigger".
(For example, registering a model with the ORM, or adding routes.)
@kurtbrose
kurtbrose / inherit_annotations.py
Last active November 14, 2023 22:16
class decorator to inherit annotations from base-classes
def inherit_annotations(cls):
"""
Inherit annotations from all base classes according to method-resolution-order.
This is the same way that type checkers will interpret annotations.
This allows for other class decorators such as attr.define() or dataclasses.dataclass()
to see the inherited annotations from plain-vanilla python classes. This, in turn,
allows base classes defining common fields to be shared among different class-decorator-annotation
libraries.
"""
@kurtbrose
kurtbrose / auto_orm.py
Created January 25, 2023 21:55
Helper for converting type annotations into sqlalchemy columns
"""
This module is a helper for converting a dataclass-like annotation class into a sqlalchemy ORM.
"""
from dataclasses import dataclass
from datetime import datetime
import enum
import functools
import inspect
import re
import types
@kurtbrose
kurtbrose / dotenv.py
Last active January 18, 2023 01:35
file for parsing .env files in python
"""
Utility for parsing .env files, as used by docker-compose and a few others.
"""
import re
QUOTED_STRING = r'("(?:(\\.|[^"\\])*)")'
SINGLE_QUOTED_STRING = r"('(?:(\\.|[^'\\])*)')"
VAL = fr'([^\s]+|{QUOTED_STRING}|{SINGLE_QUOTED_STRING})'
LINE = fr'^\s*(?P<key>{VAL})\s*=\s*(?P<val>{VAL})\s*(#.*)?$'
@kurtbrose
kurtbrose / tags.py
Created August 31, 2022 23:11
python 3 module __getattr__ is neat
from dataclasses import dataclass, field
from typing import Union
@dataclass
class _Tag:
name: str
attributes: dict[str, str] = field(default_factory=dict)
children: tuple[Union["Tag", str]] = ()
@kurtbrose
kurtbrose / stress_test.ts
Last active March 10, 2022 05:17
playing around with typescript
// a First is a function which takes two arguments
// of any type, and returns the type of the first argument
type First<T, U> = (a: T, b: U) => T
// as a non-trivial example, add_timedelta(time, timedelta) returns time
// doubler is parameterized on <T, U>, passes those parameters through to First
// typescript can figure out that f(f(a, b), b) is type correct
// since f is of type First, then it will return the same type as its first argument
// note we don't have ANY concrete types yet
@kurtbrose
kurtbrose / sicp_ch_3.rkt
Created August 29, 2021 15:27
working my way through structure and interpretation of computer programs, ch 3
#lang sicp
(define balance 100)
(define (withdraw amount)
(if (>= balance amount)
(begin (set! balance (- balance amount))
balance)
"Insufficient funds"))