Make context decorator frames identify the context manager (#186502)
Python tracebacks use a frame's code object name, not the wrapper function's __name__ metadata. torch.utils._contextlib.context_decorator used nested wrappers named decorate_context and generator_context for every context-manager decorator, so tracebacks could not distinguish no_grad, inference_mode, and other context managers. Rename the generated wrapper code object at decoration time using the context manager name. This keeps functools.wraps metadata for the decorated function intact while making traceback frames report the context manager that is actually active. Generator wrappers use the same path. Fixes #118747 Generated by my agent Test Plan: python test/test_utils.py TestTraceback.test_context_decorator_traceback_frame_name TestTraceback.test_context_decorator_generator_traceback_frame_name python test/test_utils.py TestTraceback python test/test_autograd.py TestAutograd.test_no_grad TestAutograd.test_set_grad_generator_functions TestAutograd.test_set_grad_generator_functions_recursive lintrunner -a Pull Request resolved: https://github.com/pytorch/pytorch/pull/186502 Approved by: https://github.com/karthickai
J
Jason Ansel committed
b9d5675c1a34837fd3bc508561b07652b82327bb
Parent: ed9f869
Committed by PyTorch MergeBot <pytorchmergebot@users.noreply.github.com>
on 8/23/2026, 9:03:53 PM