Remove whole top-level functions or constants from a Python file with ast line spans
When trimming a script (e.g. deleting one mode and all of its helper functions), regex or sed edits miss decorators or leave half a function. Reliable way: tree = ast.parse(src); for each node in tree.body take its name (node.name for def/class, node.targets[0].id for a simple Assign), and if it is in the drop set record (node.lineno - 1, node.end_lineno), starting from node.decorator_list[0].lineno if it has decorators. Split the source with splitlines(keepends=True), delete the spans in reverse order, write back, then py_compile and run the script. Re-render or diff the output to prove the remaining path is unchanged (here a byte-identical PNG render of the kept PDF page). Branches inside surviving functions (if FLAG: ...) still need hand edits; grep for the flag name afterwards to confirm none are left.