Use protocols instead of importlib.abc.Loader/MetaPathFinder/PathEntryFinder (#11890)

This commit is contained in:
Anderson Bravalheri
2024-05-12 10:58:33 +01:00
committed by GitHub
parent 6565e8a0a0
commit b42e3b2e89
8 changed files with 72 additions and 25 deletions

View File

@@ -1,7 +1,14 @@
from __future__ import annotations
import importlib.abc
import importlib.util
import pathlib
import sys
import zipfile
from collections.abc import Sequence
from importlib.machinery import ModuleSpec
from types import ModuleType
from typing_extensions import Self
# Assert that some Path classes are Traversable.
if sys.version_info >= (3, 9):
@@ -11,3 +18,30 @@ if sys.version_info >= (3, 9):
traverse(pathlib.Path())
traverse(zipfile.Path(""))
class MetaFinder:
@classmethod
def find_spec(cls, fullname: str, path: Sequence[str] | None, target: ModuleType | None = None) -> ModuleSpec | None:
return None # simplified mock for demonstration purposes only
class PathFinder:
@classmethod
def path_hook(cls, path_entry: str) -> type[Self]:
return cls # simplified mock for demonstration purposes only
@classmethod
def find_spec(cls, fullname: str, target: ModuleType | None = None) -> ModuleSpec | None:
return None # simplified mock for demonstration purposes only
class Loader:
@classmethod
def load_module(cls, fullname: str) -> ModuleType:
return ModuleType(fullname)
sys.meta_path.append(MetaFinder)
sys.path_hooks.append(PathFinder.path_hook)
importlib.util.spec_from_loader("xxxx42xxxx", Loader)