def toggled_optimizer(self, optimizer: Union[Optimizer, LightningOptimizer]) -> Generator:
        """Makes sure only the gradients of the current optimizer's parameters are calculated in the training step to
        prevent dangling gradients in multiple-optimizer setup. Combines :meth:`toggle_optimizer` and
        :meth:`untoggle_optimizer` into context manager.

        Args:
            optimizer: The optimizer to toggle.

        Example::

            def training_step(...):
                opt = self.optimizers()
                with self.toggled_optimizer(opt):
                    loss = ...
                    opt.zero_grad()
                    self.manual_backward(loss)
                    opt.step()

        """
        self.toggle_optimizer(optimizer)
        try:
            yield
        finally:
            self.untoggle_optimizer(optimizer)
Makes sure only the gradients of the current optimizer's parameters are calculated in the training step to
        prevent dangling gradients in multiple-optimizer setup. Combines :meth:`toggle_optimizer` and
        :meth:`untoggle_optimizer` into context manager.

        Args:
            optimizer: The optimizer to toggle.

        Example::

            def training_step(...):
                opt = self.optimizers()
                with self.toggled_optimizer(opt):
                    loss = ...
                    opt.zero_grad()
                    self.manual_backward(loss)
                    opt.step()

        
src/lightning/pytorch/core/module.py