code: def patch_instances(fields):
      """
      A contextmanager, under which the Instances class in detectron2 is replaced
      by a statically-typed scriptable class, defined by `fields`.
      See more in `scripting_with_instances`.
      """
  
      with tempfile.TemporaryDirectory(
          prefix="detectron2"
      ) as dir, tempfile.NamedTemporaryFile(
          mode="w",
          encoding="utf-8",
          suffix=".py",
          dir=dir,
          delete=False,
      ) as f:
          try:
              # Objects that use Instances should not reuse previously-compiled
              # results in cache, because `Instances` could be a new class each time.
              _clear_jit_cache()
  
              cls_name, s = _gen_instance_module(fields)
              f.write(s)
              f.flush()
              f.close()
  
              module = _import(f.name)
              new_instances = getattr(module, cls_name)
              _ = torch.jit.script(new_instances)
              # let torchscript think Instances was scripted already
              Instances.__torch_script_class__ = True
              # let torchscript find new_instances when looking for the jit type of Instances
              Instances._jit_override_qualname = (
                  torch._jit_internal._qualified_name(new_instances)
              )
  
              _add_instances_conversion_methods(new_instances)
              yield new_instances
          finally:
              try:
                  del Instances.__torch_script_class__
                  del Instances._jit_override_qualname
              except AttributeError:
                  pass
              sys.modules.pop(module.__name__)
  
file_path: detectron2/detectron2/export/torchscript_patch.py
imports: import os
  import sys
  import tempfile
  from contextlib import ExitStack, contextmanager
  from copy import deepcopy
  from unittest import mock
  import torch
  from torch import nn
  import detectron2
  from detectron2.structures import Boxes, Instances
  from detectron2.utils.env import _import_file
label_desc: Use image node_id 3 for calling a global function with example usage: patch_instances(fields) without return types