Last active
June 27, 2026 11:49
-
-
Save internetimagery/06fdac60ab5b9766b56a8c626a40c41b to your computer and use it in GitHub Desktop.
Simple inline codegen. Generate things like typing overloads in-file by running the file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from typing import overload, Any | |
| # <gen_get_overloads codegen> | |
| # Anything in here is replaced with the result of gen_get_overloads() | |
| # </gen_get_overloads> | |
| def get(val: Any) -> Any: | |
| return val | |
| if __name__ == "__main__": | |
| import re, textwrap | |
| def gen_get_overloads(): | |
| return "\n\n".join( | |
| f"@overload\ndef get(val: {typ}) -> {typ}:\n ..." | |
| for typ in ("str", "int", "bool") | |
| ) | |
| with open(__file__, "r") as h: | |
| code = h.read() | |
| newcode, n = re.subn( | |
| r"(?ms)((^[ \t]*)# *<([^ ]+) +codegen>[ \t]*$).*?(^[ \t]*# *</\3>[ \t]*$)", | |
| lambda m, g=globals(): f"{m.group(1)}\n{textwrap.indent(g[m.group(3)](), m.group(2))}\n{m.group(4)}", | |
| code, | |
| ) | |
| if newcode != code: | |
| compile(newcode, __file__, "exec") # Sanity check the syntax is still valid | |
| with open(__file__ + ".codegen.bak", "w") as h: h.write(code) | |
| with open(__file__, "w") as h: h.write(newcode) | |
| print(f"Updated {n} codegen blocks!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment