src/transformers/dynamic_module_utils.py/get_class_in_module
def get_class_in_module(class_name, module_path):
    """
    Import a module on the cache directory for modules and extract a class from it.
    """
    with tempfile.TemporaryDirectory() as tmp_dir:
        module_dir = Path(HF_MODULES_CACHE) / os.path.dirname(module_path)
        module_file_name = module_path.split(os.path.sep)[-1] + ".py"

        # Copy to a temporary directory. We need to do this in another process to avoid strange and flaky error
        # `ModuleNotFoundError: No module named 'transformers_modules.[module_dir_name].modeling'`
        shutil.copy(f"{module_dir}/{module_file_name}", tmp_dir)
        # On Windows, we need this character `r` before the path argument of `os.remove`
        cmd = f'import os; os.remove(r"{module_dir}{os.path.sep}{module_file_name}")'
        # We don't know which python binary file exists in an environment. For example, if `python3` exists but not
        # `python`, the call `subprocess.run(["python", ...])` gives `FileNotFoundError` (about python binary). Notice
        # that, if the file to be removed is not found, we also have `FileNotFoundError`, but it is not raised to the
        # caller's process.
        try:
            subprocess.run(["python", "-c", cmd])
        except FileNotFoundError:
            try:
                subprocess.run(["python3", "-c", cmd])
            except FileNotFoundError:
                pass

        # copy back the file that we want to import
        shutil.copyfile(f"{tmp_dir}/{module_file_name}", f"{module_dir}/{module_file_name}")

        # import the module
        module_path = module_path.replace(os.path.sep, ".")
        module = importlib.import_module(module_path)

        return getattr(module, class_name)