Skip to content

Instantly share code, notes, and snippets.

@a-recknagel
a-recknagel / run_once.py
Created April 24, 2023 12:12
Scoped decorator
from functools import wraps
SENTINEL = object()
def run_once(func):
"""Decorator which ensures that a function is only executed a single time."""
class Scope:
locals = {"result": SENTINEL}
@a-recknagel
a-recknagel / my_package.ext.__init__.py
Created March 1, 2023 15:21
warn when entering extra-install-requiring-section in a lib
import warnings
from importlib import import_module
from importlib.metadata import requires
from packaging.requirements import Requirement
MY_LIB = "my_lib"
CURRENT_EXTRA = "my_extra"
@a-recknagel
a-recknagel / stream.py
Last active February 8, 2023 12:56
lazy pipeline object
from typing import Iterable
import itertools
class Stream:
def __init__(self, stream: Iterable):
self.stream = stream
def __iter__(self):
yield from self.stream
@a-recknagel
a-recknagel / sample.py
Last active January 17, 2023 23:16
fetch annotations defined in __init__
import ast
import inspect
class InitAnnotations(ast.NodeVisitor):
def __init__(self, locals_, globals_):
self.globals = globals_
self.locals = locals_
self.annotations = {}
@a-recknagel
a-recknagel / plugins.py
Created January 13, 2023 22:15
Batchwise factory for fastapi routes
from typing import Literal
from fastapi import FastAPI, Depends
from pydantic import BaseModel
import uvicorn
app = FastAPI()
class Request(BaseModel):
data: str
@a-recknagel
a-recknagel / .env
Last active January 6, 2023 09:23
Config example with custom toml loaders and the builtin env loader
MY_APP_APP__PASSWORD="secret_foo"
MY_APP_DB__PASSWORD="secret_bar"
@a-recknagel
a-recknagel / sensitive.py
Created July 5, 2022 08:51
how I'd like a no-op type to behave
from pydantic import BaseModel
Sensitive = ...
class Config(BaseModel):
user: str
password: Sensitive[str]
@a-recknagel
a-recknagel / test.py
Last active May 27, 2022 20:42
pydantic validator example
import json
from pydantic import BaseModel, validator
class FirstLevel(BaseModel):
bar: "SecondLevel"
foo: int
@validator("foo")
@a-recknagel
a-recknagel / bad_test.py
Last active October 25, 2021 11:26
bad test - good test
# adding widgets to my app
import my_app
def foo(user_id: int, num_widgets: int):
user = my_app.get_user(user_id)
widgets = []
for _ in range(num_widgets):
widgets.append(my_app.create_widget(user))
my_app.bootstrap(widgets)
@a-recknagel
a-recknagel / simple.py
Last active June 29, 2021 08:32
fastapi with custom classes in response
from fastapi import FastAPI
from pydantic import BaseModel, BaseConfig
app = FastAPI()
BaseConfig.arbitrary_types_allowed = True
class Foo:
def __init__(self, x: int):
self.x = x