def _make_redirector(stub_module_name: str, target_module_name: str | None):
  """Builds a redirector module for the given target module."""

  # pylint: disable=import-outside-toplevel
  import importlib
  import importlib.machinery
  import importlib.util
  import sys
  # pylint: enable=import-outside-toplevel

  spec = importlib.machinery.ModuleSpec(name=stub_module_name, loader=None)
  mod = importlib.util.module_from_spec(spec)
  mod.__doc__ = f"""Redirector module for {stub_module_name}."""

  if target_module_name is not None:

    def redirecting_getattr(name: str):
      if name.startswith("__"):
        raise AttributeError(
            f"module {repr(stub_module_name)} has no attribute '{name}'"
        )

      reference_module = importlib.import_module(target_module_name)
      return getattr(reference_module, name)

    def redirecting_dir():
      reference_module = importlib.import_module(target_module_name)
      return dir(reference_module)

    mod.__getattr__ = redirecting_getattr
    mod.__dir__ = redirecting_dir

  stub_parent_name, mod_name = stub_module_name.rsplit(".", 1)
  setattr(sys.modules[stub_parent_name], mod_name, mod)

  sys.modules[stub_module_name] = mod
Builds a redirector module for the given target module.
penzai/experimental/v2/__init__.py