Skip to content

Commit cf20ac9

Browse files
committed
feat: implement _find_spec function to enhance module spec retrieval
1 parent bfc76d6 commit cf20ac9

File tree

1 file changed

+27
-2
lines changed

1 file changed

+27
-2
lines changed

src/awepatch/_module.py

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
from collections import defaultdict
77
from dataclasses import dataclass
88
from importlib.abc import MetaPathFinder, SourceLoader
9-
from importlib.util import find_spec
109

1110
from awepatch._utils import (
1211
AWEPATCH_DEBUG,
@@ -99,6 +98,32 @@ def find_spec(
9998
return self._modules.get(fullname, None)
10099

101100

101+
def _find_spec(name: str) -> ModuleSpec | None:
102+
"""Find a module's spec."""
103+
if name in sys.modules:
104+
# The module is already imported, so we can skip the finders and just
105+
# return the spec from sys.modules.
106+
return sys.modules[name].__spec__
107+
108+
meta_path = sys.meta_path
109+
if not meta_path:
110+
import warnings
111+
112+
warnings.warn("sys.meta_path is empty", ImportWarning, stacklevel=2)
113+
114+
for finder in meta_path:
115+
try:
116+
find_spec = finder.find_spec
117+
except AttributeError:
118+
continue
119+
else:
120+
spec = find_spec(name, None)
121+
if spec is not None:
122+
return spec
123+
else:
124+
return None
125+
126+
102127
class ModulePatcher(AbstractPatcher):
103128
# Module is not thread-safe for patching. Please ensure no other thread
104129
# is importing the target module during patching.
@@ -111,7 +136,7 @@ def _get_module_info(self, module: str) -> ModuleInfo:
111136
if (module_info := self._modules.get(module)) is not None:
112137
return module_info
113138

114-
spec = find_spec(module)
139+
spec = _find_spec(module)
115140
if spec is None or spec.origin is None:
116141
raise ValueError(f"Module {module} not found")
117142

0 commit comments

Comments
 (0)