Skip to content

Instantly share code, notes, and snippets.

@MCausc78
Created July 10, 2025 18:37
Show Gist options
  • Save MCausc78/850592daaf6a57f61092a8da28659507 to your computer and use it in GitHub Desktop.
Save MCausc78/850592daaf6a57f61092a8da28659507 to your computer and use it in GitHub Desktop.
Reprompiled (generating very fast repr function at runtime)
from __future__ import annotations
import logging
from random import Random
from typing import Any, Optional, TYPE_CHECKING
from pydantic import BaseModel
if TYPE_CHECKING:
from collections.abc import Callable
logging.basicConfig(level=logging.DEBUG)
_log = logging.getLogger("reprompiled")
def is_none(value: Optional[Any]) -> bool:
return value is None
def is_falsy(value: Any) -> bool:
return not bool(value)
def is_truthy(value: Any) -> bool:
return bool(value)
def eq(to: Any) -> Callable[[Any], bool]:
def func(value: Any) -> bool:
return value == to
return func
def ne(to: Any) -> Callable[[Any], bool]:
def func(value: Any) -> bool:
return value != to
return func
def gt(to: Any) -> Callable[[Any], bool]:
def func(value: Any) -> bool:
return value > to
return func
def lt(to: Any) -> Callable[[Any], bool]:
def func(value: Any) -> bool:
return value < to
return func
def ge(to: Any) -> Callable[[Any], bool]:
def func(value: Any) -> bool:
return value >= to
return func
def le(to: Any) -> Callable[[Any], bool]:
def func(value: Any) -> bool:
return value <= to
return func
def one_of(*items: Any) -> Callable[[Any], bool]:
def func(value: Any) -> bool:
return value in items
return func
def none_of(*items: Any) -> Callable[[Any], bool]:
def func(value: Any) -> bool:
return value not in items
return func
def all_of(*checks: Callable[[Any], bool]) -> Callable[[Any], bool]:
def func(value: Any) -> bool:
for check in checks:
if not check(value):
return False
return True
return func
def any_of(*checks: Callable[[Any], bool]) -> Callable[[Any], bool]:
def func(value: Any) -> bool:
for check in checks:
if check(value):
return True
return False
return func
def not_(check: Callable[[Any], bool]) -> Callable[[Any], bool]:
def func(value: Any) -> bool:
return not check(value)
return func
def has(required: Any) -> Callable[[Any], bool]:
def func(value: Any) -> bool:
return required in value
return func
_random = Random(1)
_used_names = set()
class ReprompileMixin:
__slots__ = ()
__repr__: Callable[[], str]
def reprompile(
*attrs: str,
omit_if: Optional[dict[str, Callable[[Any], bool]]] = None,
type_name: Callable[[Any], str] = lambda self: type(self).__name__,
rename: Optional[dict[str, str]] = None,
) -> type[ReprompileMixin]:
while True:
name = ''.join(_random.choices('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', k=16))
if name not in _used_names:
break
_used_names.add(name)
if omit_if is None:
omit_if = {}
if rename is None:
rename = {}
else:
rename = {k: v for k, v in rename.items() if k != v}
fname = "_repr_" + name
env: dict[str, Any] = {
fname + "_tn": type_name,
}
for k, v in omit_if.items():
env[fname + "_omit_if_for_" + k] = v
for k, v in rename.items():
env[fname + "_rename_of_" + k] = v
code = ""
for attr in attrs:
if attr in omit_if:
code += '{0}_omit_if_for_{1}(self.{1})or '.format(fname, attr)
if attr in rename:
code += "(ret:=ret+' '+{0}_rename_of_{1}".format(fname, attr)
else:
code += "(ret:=ret+' {0}'".format(attr)
code += f"+'='+repr(self.{attr}));"
code = (
"def {0}(self, /):ret='<'+{0}_tn(self);{1}return ret+'>'".format(
fname,
code,
)
if code else
"def {0}(self, /):return'<'+{0}_tn(self)+'>'".format(fname)
)
_log.debug("Generating _ReprompileMixin_%s: repr=%s", name, code)
exec(code, env, env)
fn = env[fname]
return type(
"_ReprompileMixin_" + name,
(ReprompileMixin,),
{"__repr__": fn},
)
class MyThing(
reprompile(
'a',
'b',
'c',
omit_if={
"d": any_of(
has(2),
has(4),
has(6),
),
},
rename={
"b": "a_string",
},
),
BaseModel,
):
a: int
b: str
c: list[dict[str, int]]
d: list[int]
thing = MyThing(a=42, b='balls', c=[{"hello": 69}], d=[1])
print(repr(thing))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment