Skip to content

Instantly share code, notes, and snippets.

@mahdilamb
Last active January 13, 2026 23:26
Show Gist options
  • Select an option

  • Save mahdilamb/e0f21d80e61e93892637d0945d63dda4 to your computer and use it in GitHub Desktop.

Select an option

Save mahdilamb/e0f21d80e61e93892637d0945d63dda4 to your computer and use it in GitHub Desktop.
"""
Live utility for converting `.model_validate({...})` calls into
model constructor calls with snake_case keyword arguments.
The module watches itself for changes, reloads on save, transforms
the code in `SAMPLE` and copies it to the clipboard.
"""
import importlib.util
import os
import re
import subprocess
import sys
import time
SAMPLE = """
"""
a = re.compile(r"(.*?)(?:\.model_validate\([\s{]*)(.*?)}\s*\)", re.S | re.M)
b = re.compile(r"\"([^\"]*?)\":")
def print_output():
try:
cls, body = next(a.finditer(SAMPLE)).groups()
for grp in reversed(tuple(b.finditer(body))):
body = (
body[: grp.start()]
+ re.sub(r"(?<!^)(?=[A-Z])", "_", grp.group(1)).lower()
+ "="
+ body[grp.end() :]
)
return (f"{cls}(" + body + ")").strip()
except Exception as e:
print(e)
if __name__ == "__main__":
mtime = None
module_name = "_unvalidate"
while True:
if mtime != (current_mtime := os.stat(__file__).st_mtime):
spec = importlib.util.spec_from_file_location(module_name, __file__)
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
spec.loader.exec_module(module)
print()
data = module.print_output()
subprocess.run("pbcopy", text=True, input=data)
print(data)
print()
mtime = current_mtime
time.sleep(0.1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment