"""The Python side of every contract, serving batches on stdin and stdout. The Gleam runner starts it once per run (test/contract/support.py has the framing). Each contract module beside this file exports ``PYTHON_OPS``, a map from an operation name to a function from a batch of cases to a batch of results. Diagnostics go to stderr, never stdout, which carries the answers. """ import importlib from pathlib import Path import sys import traceback sys.path.insert(0, str(Path(__file__).resolve().parent)) sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "python")) from support import read_message, write_message # noqa: E402 def main() -> int: requests = sys.stdin.buffer answers = sys.stdout.buffer sys.stdout = sys.stderr while True: try: request = read_message(requests) except EOFError: return 0 try: assert isinstance(request, dict) module = importlib.import_module(request["contract"]) op = module.PYTHON_OPS[request["op"]] answer: object = {"results": op(request["cases"])} except Exception: answer = {"error": traceback.format_exc()} write_message(answers, answer) if __name__ == "__main__": sys.exit(main())