#!/usr/bin/env python3 """Check type_new_set_module's module declaration and lookup timing.""" import re from pathlib import Path source = Path("cpython/Objects/typeobject.c").read_text() match = re.search( r"\nstatic int\ntype_new_set_module\(PyTypeObject \*type\)\n\{(.*?)\n\}", source, re.S, ) assert match, "type_new_set_module definition missing" body = re.sub(r"/\*.*?\*/|//[^\n]*", "", match.group(1), flags=re.S) assert re.match( r"\s*PyObject \*globals;" r"\s*PyObject \*module;" r"\s*int r = PyDict_Contains\(type->tp_dict, &_Py_ID\(__module__\)\);", body, ), "type_new_set_module: module must be in the opening declaration block (C89)" assert len(re.findall(r"\bPyObject\s*\*\s*module\b", body)) == 1, ( "declare module exactly once" ) assert len(re.findall(r"\bmodule\s*=(?!=)", body)) == 1, ( "assign module exactly once" ) expected = """ PyObject *globals; PyObject *module; int r = PyDict_Contains(type->tp_dict, &_Py_ID(__module__)); if (r < 0) { return -1; } if (r > 0) { return 0; } globals = PyEval_GetGlobals(); if (globals == NULL) { return 0; } module = PyDict_GetItemWithError(globals, &_Py_ID(__name__)); if (module == NULL) { if (PyErr_Occurred()) { return -1; } return 0; } if (PyDict_SetItem(type->tp_dict, &_Py_ID(__module__), module) < 0) { return -1; } return 0; """ assert body.split() == expected.split(), ( "type_new_set_module: preserve lookup/assignment order, early returns, " "and module consumption" ) print("type_new_set_module module C89 declaration and lookup timing: PASS")