Skip to content

Instantly share code, notes, and snippets.

@clbarnes
Last active June 17, 2025 11:15
Show Gist options
  • Save clbarnes/102bad110cc5a4d5bdeaa864749afe02 to your computer and use it in GitHub Desktop.
Save clbarnes/102bad110cc5a4d5bdeaa864749afe02 to your computer and use it in GitHub Desktop.
Automatically generate Literal annotations for cmap names a la https://github.com/pyapp-kit/cmap/issues/105
from pathlib import Path
import json
scripts_dir = Path(__file__).resolve().parent
module_dir = scripts_dir.parent.joinpath("src", "cmap")
data_dir = module_dir.joinpath("data")
names = []
for rel_path in sorted(data_dir.glob("*/record.json")):
p = data_dir.joinpath(rel_path)
prefix_name = rel_path.parent.name
with p.open() as f:
d = json.load(f)
for subname in sorted(d.get("colormaps", [])):
for suffix in ["", "_r"]:
for prefix in ["", f"{prefix_name}:"]:
names.append(f"{prefix}{subname.lower()}{suffix}")
names_fmt = "".join(" " * 4 + '"{n}",\n' for n in names)
script = f'''
"""Type annotation for literal colormap names.
Auto-generated by make_cmapnames.py : DO NOT EDIT.
"""
from typing import Literal
type ColormapName = Literal[
{names_fmt}]
'''.lstrip()
module_dir.joinpath("_colormapname.py").open("w").write_text(script)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment