22
33import ast
44import sys
5- import threading
65from collections import defaultdict
76from importlib .abc import MetaPathFinder , SourceLoader
7+ from importlib .machinery import PathFinder
88from typing import Self
99
1010from awepatch .utils import (
3333
3434class _AwepatchSourceLoader (SourceLoader ):
3535 def __init__ (
36- self , fullname : str , origin : str , patches : list [CompiledPatch ]
36+ self ,
37+ fullname : str ,
38+ origin : str ,
39+ patches : list [CompiledPatch ],
3740 ) -> None :
3841 self ._fullname = fullname
39- self ._patches = patches
4042 self ._origin = origin
4143 self ._path = origin
44+ self ._patches = patches
4245
4346 def get_filename (self , fullname : str ) -> str :
4447 return self ._origin
@@ -87,12 +90,6 @@ def source_to_code(
8790
8891
8992class _AwepatchSpecFinder (MetaPathFinder ):
90- # lock[0] is threading.Lock(), but initialized lazily to avoid importing threading
91- # very early at startup, because there are gevent-based applications that need to be
92- # first to import threading by themselves.
93- # See https://github.com/pypa/virtualenv/issues/1895 for details.
94- _lock : threading .Lock = threading .Lock ()
95-
9693 def __init__ (self , patches : dict [str , list [CompiledPatch ]]) -> None :
9794 super ().__init__ ()
9895 self ._patches = patches
@@ -105,23 +102,21 @@ def find_spec(
105102 / ,
106103 ) -> ModuleSpec | None :
107104 if fullname in self ._patches :
108- from importlib .machinery import PathFinder
109-
110- with _AwepatchSpecFinder ._lock :
111- spec = PathFinder .find_spec (fullname , path , target )
112- if spec is not None and spec .origin is not None :
113- spec .loader = _AwepatchSourceLoader (
114- fullname ,
115- spec .origin ,
116- self ._patches [fullname ],
117- )
118-
119- return spec
120-
105+ spec = PathFinder .find_spec (fullname , path , target )
106+ if spec is not None and spec .origin is not None :
107+ spec .loader = _AwepatchSourceLoader (
108+ fullname ,
109+ spec .origin ,
110+ self ._patches [fullname ],
111+ )
112+ return spec
121113 return None
122114
123115
124116class ModulePatcher (AbstractPatcher ):
117+ # Module is not thread-safe for patching. Please ensure no other thread
118+ # is importing the target module during patching.
119+
125120 def __init__ (self ) -> None :
126121 self ._patches : defaultdict [str , list [CompiledPatch ]] = defaultdict (list )
127122 self ._finder : _AwepatchSpecFinder | None = None
0 commit comments