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
from typing import (
Protocol,
Callable,
TypeVar,
ParamSpec,
overload,
Concatenate,
runtime_checkable
)
@kurtbrose
kurtbrose / auto_public_id.py
Created November 25, 2024 19:49
Globally unique public ids in sqlalchemy + postgres
import enum
from datetime import datetime
from sqlalchemy import Column
from sqlalchemy import DateTime
from sqlalchemy import Enum
from sqlalchemy import event
from sqlalchemy import func
from sqlalchemy import select
from sqlalchemy import String
@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 December 23, 2024 17:52
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]] = ()