This change guards GIL check and decref for objects behind a check that the Python runtime still exists.
This can happen if a static variable outlives the python runtime and is destroyed later. This happens when the user uses the recommended way to create custom exceptions from https://pybind11.readthedocs.io/en/stable/advanced/exceptions.html as static py::exception<MyCustomException> exc(m, "MyCustomError");
We don't have the final conclusion yet but we're definitely not going to do this (fixing the lifetime of the obejcts instead).
See https://github.com/pytorch/pytorch/pull/106401 for more details on the discussion.
Description
This change guards GIL check and decref for objects behind a check that the Python runtime still exists. This can happen if a static variable outlives the python runtime and is destroyed later. This happens when the user uses the recommended way to create custom exceptions from https://pybind11.readthedocs.io/en/stable/advanced/exceptions.html as
static py::exception<MyCustomException> exc(m, "MyCustomError");
In particular, this change fixes the segfault described at https://github.com/pytorch/pytorch/pull/106083 (when working on upgrading PyTorch to 3.12)
Suggested changelog entry:
Skip calling Python decref when the Python runtime is already dead.