class_docstr: Holds a collection of stateful objects.
class_docstr_tok: ["Holds","a","collection","of","stateful","objects","."]
docstr: Add ``obj`` to the bag and preserve its state in ``state_dict``.
  
  :param name:
      The attribute name to refer to ``obj``.
  :param obj:
      The object to add.
  :param state_handler:
      The handler to load and extract the state of ``obj``. If ``None``
      and ``obj`` is of type :class:`Stateful`, then its ``state_dict``
      will be used; otherwise, ``obj`` will be preserved as is.
docstr_tok: ["Add","``","obj","``","to","the","bag","and","preserve","its","state","in","``","state_dict","``",".",":","param","name",":","The","attribute","name","to","refer","to","``","obj","``",".",":","param","obj",":","The","object","to","add",".",":","param","state_handler",":","The","handler","to","load","and","extract","the","state","of","``","obj","``",".","If","``","None","``","and","``","obj","``","is","of","type",":","class",":","`","Stateful","`",",","then","its","``","state_dict","``","will","be","used",";","otherwise",",","``","obj","``","will","be","preserved","as","is","."]
code: def register_stateful(
      self,
      name: str,
      obj: Any,
      state_handler: Optional[StateHandler] = None,
  ) -> None:
      """Add ``obj`` to the bag and preserve its state in ``state_dict``.
  
      :param name:
          The attribute name to refer to ``obj``.
      :param obj:
          The object to add.
      :param state_handler:
          The handler to load and extract the state of ``obj``. If ``None``
          and ``obj`` is of type :class:`Stateful`, then its ``state_dict``
          will be used; otherwise, ``obj`` will be preserved as is.
      """
      if hasattr(self, name):
          raise AttributeError(
              f"`{type(self).__name__}` object already has an attribute '{name}'."
          )
  
      self.stateful_objects[name] = (obj, state_handler)
  
imports: from __future__ import annotations
  from abc import ABC, abstractmethod
  from typing import Any, Dict, Mapping, Optional, Protocol, Tuple, final, runtime_checkable
  from torch.distributed.fsdp import FullyShardedDataParallel
  from torch.nn import Module
  from torch.optim import Optimizer
  from fairseq2.typing import finaloverride
label_desc: Use image node_id 5 for calling the StatefulObjectBag obj's underlying member method code with example usage: obj.register_stateful(name, obj, state_handler) without return types