wrapt 2.4.0.dev2__cp315-cp315t-win32.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
wrapt/importer.py ADDED
@@ -0,0 +1,310 @@
1
+ """This module implements a post import hook mechanism styled after what is
2
+ described in PEP-369. Note that it doesn't cope with modules being reloaded.
3
+
4
+ """
5
+
6
+ import importlib.metadata
7
+ import sys
8
+ import threading
9
+ from collections.abc import Callable
10
+ from importlib.util import find_spec
11
+
12
+ from .__wrapt__ import BaseObjectProxy
13
+
14
+ # The dictionary registering any post import hooks to be triggered once
15
+ # the target module has been imported. Once a module has been imported
16
+ # and the hooks fired, the list of hooks recorded against the target
17
+ # module will be truncated but the list left in the dictionary. This
18
+ # acts as a flag to indicate that the module had already been imported.
19
+
20
+ _post_import_hooks: dict[str, list[Callable]] = {}
21
+ _post_import_hooks_init = False
22
+ _post_import_hooks_lock = threading.RLock()
23
+
24
+ # Register a new post import hook for the target module name. This
25
+ # differs from the PEP-369 implementation in that it also allows the
26
+ # hook function to be specified as a string consisting of the name of
27
+ # the callback in the form 'module:function'. This will result in a
28
+ # proxy callback being registered which will defer loading of the
29
+ # specified module containing the callback function until required.
30
+
31
+
32
+ def _create_import_hook_from_string(name):
33
+ def import_hook(module):
34
+ module_name, function = name.split(":")
35
+ attrs = function.split(".")
36
+ __import__(module_name)
37
+ callback = sys.modules[module_name]
38
+ for attr in attrs:
39
+ callback = getattr(callback, attr)
40
+ return callback(module)
41
+
42
+ return import_hook
43
+
44
+
45
+ def register_post_import_hook(hook, name):
46
+ """
47
+ Register a post import hook for the target module `name`. The `hook`
48
+ function will be called once the module is imported and will be passed the
49
+ module as argument. If the module is already imported, the `hook` will be
50
+ called immediately. If you also want to defer loading of the module containing
51
+ the `hook` function until required, you can specify the `hook` as a string in
52
+ the form 'module:function'. This will result in a proxy hook function being
53
+ registered which will defer loading of the specified module containing the
54
+ callback function until required.
55
+ """
56
+
57
+ # Create a deferred import hook if hook is a string name rather than
58
+ # a callable function.
59
+
60
+ if isinstance(hook, str):
61
+ hook = _create_import_hook_from_string(hook)
62
+
63
+ with _post_import_hooks_lock:
64
+ # Automatically install the import hook finder if it has not already
65
+ # been installed.
66
+
67
+ global _post_import_hooks_init
68
+
69
+ if not _post_import_hooks_init:
70
+ _post_import_hooks_init = True
71
+ sys.meta_path.insert(0, ImportHookFinder())
72
+
73
+ # Check if the module is already imported. If not, register the hook
74
+ # to be called after import.
75
+
76
+ module = sys.modules.get(name, None)
77
+
78
+ if module is None:
79
+ _post_import_hooks.setdefault(name, []).append(hook)
80
+
81
+ # If the module is already imported, we fire the hook right away. Note that
82
+ # the hook is called outside of the lock to avoid deadlocks if code run as a
83
+ # consequence of calling the module import hook in turn triggers a separate
84
+ # thread which tries to register an import hook.
85
+
86
+ if module is not None:
87
+ hook(module)
88
+
89
+
90
+ # Register post import hooks defined as package entry points.
91
+
92
+
93
+ def discover_post_import_hooks(group):
94
+ """
95
+ Discover and register post import hooks defined as package entry points
96
+ in the specified `group`. The group should be a string that matches the
97
+ entry point group name used in the package metadata.
98
+ """
99
+
100
+ try:
101
+ # Python 3.10+ style with select parameter
102
+ entrypoints = importlib.metadata.entry_points(group=group)
103
+ except TypeError:
104
+ # Python 3.8-3.9 style that returns a dict
105
+ entrypoints = importlib.metadata.entry_points().get(group, ())
106
+
107
+ for entrypoint in entrypoints:
108
+ callback = entrypoint.load() # Use the loaded callback directly
109
+ register_post_import_hook(callback, entrypoint.name)
110
+
111
+
112
+ # Indicate that a module has been loaded. Any post import hooks which
113
+ # were registered against the target module will be invoked. If an
114
+ # exception is raised in any of the post import hooks, that will cause
115
+ # the import of the target module to fail.
116
+
117
+
118
+ def notify_module_loaded(module):
119
+ """
120
+ Notify that a `module` has been loaded and invoke any post import hooks
121
+ registered against the module. If the module is not registered, this
122
+ function does nothing.
123
+ """
124
+
125
+ name = getattr(module, "__name__", None)
126
+
127
+ with _post_import_hooks_lock:
128
+ hooks = _post_import_hooks.pop(name, ())
129
+
130
+ # Note that the hook is called outside of the lock to avoid deadlocks if
131
+ # code run as a consequence of calling the module import hook in turn
132
+ # triggers a separate thread which tries to register an import hook.
133
+
134
+ for hook in hooks:
135
+ hook(module)
136
+
137
+
138
+ # A custom module import finder. This intercepts attempts to import
139
+ # modules and watches out for attempts to import target modules of
140
+ # interest. When a module of interest is imported, then any post import
141
+ # hooks which are registered will be invoked.
142
+
143
+
144
+ class _ImportHookChainedLoader(BaseObjectProxy):
145
+
146
+ def __init__(self, loader):
147
+ # Explicit class in super() is used because the proxy overrides
148
+ # __class__ and MRO-related methods to delegate to the wrapped
149
+ # object, which can interfere with bare super().
150
+ super(_ImportHookChainedLoader, self).__init__(loader)
151
+
152
+ if hasattr(loader, "load_module"):
153
+ self.__self_setattr__("load_module", self._self_load_module)
154
+ if hasattr(loader, "create_module"):
155
+ self.__self_setattr__("create_module", self._self_create_module)
156
+ if hasattr(loader, "exec_module"):
157
+ self.__self_setattr__("exec_module", self._self_exec_module)
158
+
159
+ def _self_set_loader(self, module):
160
+ # Set module's loader to self.__wrapped__ unless it's already set to
161
+ # something else. Import machinery will set it to spec.loader if it is
162
+ # None, so handle None as well. The module may not support attribute
163
+ # assignment, in which case we simply skip it. Note that we also deal
164
+ # with __loader__ not existing at all. This is to future proof things
165
+ # due to proposal to remove the attribute as described in the GitHub
166
+ # issue at https://github.com/python/cpython/issues/77458. Also prior
167
+ # to Python 3.3, the __loader__ attribute was only set if a custom
168
+ # module loader was used. It isn't clear whether the attribute still
169
+ # existed in that case or was set to None.
170
+
171
+ class UNDEFINED:
172
+ pass
173
+
174
+ if getattr(module, "__loader__", UNDEFINED) in (None, self):
175
+ try:
176
+ module.__loader__ = self.__wrapped__
177
+ except AttributeError:
178
+ pass
179
+
180
+ if (
181
+ getattr(module, "__spec__", None) is not None
182
+ and getattr(module.__spec__, "loader", None) is self
183
+ ):
184
+ module.__spec__.loader = self.__wrapped__
185
+
186
+ def _self_load_module(self, fullname):
187
+ module = self.__wrapped__.load_module(fullname)
188
+ self._self_set_loader(module)
189
+ notify_module_loaded(module)
190
+
191
+ return module
192
+
193
+ # Python 3.4 introduced create_module() and exec_module() instead of
194
+ # load_module() alone. Splitting the two steps.
195
+
196
+ def _self_create_module(self, spec):
197
+ return self.__wrapped__.create_module(spec)
198
+
199
+ def _self_exec_module(self, module):
200
+ self._self_set_loader(module)
201
+ self.__wrapped__.exec_module(module)
202
+ notify_module_loaded(module)
203
+
204
+
205
+ class ImportHookFinder:
206
+
207
+ def __init__(self):
208
+ self.in_progress = {}
209
+
210
+ def find_module(self, fullname, path=None):
211
+ with _post_import_hooks_lock:
212
+ # If the module being imported is not one we have registered
213
+ # post import hooks for, we can return immediately. We will
214
+ # take no further part in the importing of this module.
215
+
216
+ if fullname not in _post_import_hooks:
217
+ return None
218
+
219
+ # When we are interested in a specific module, we will call back
220
+ # into the import system a second time to defer to the import
221
+ # finder that is supposed to handle the importing of the module.
222
+ # We set an in progress flag for the target module so that on
223
+ # the second time through we don't trigger another call back
224
+ # into the import system and cause a infinite loop.
225
+
226
+ if fullname in self.in_progress:
227
+ return None
228
+
229
+ self.in_progress[fullname] = True
230
+
231
+ # Now call back into the import system again.
232
+
233
+ try:
234
+ # For Python 3 we need to use find_spec().loader
235
+ # from the importlib.util module. It doesn't actually
236
+ # import the target module and only finds the
237
+ # loader. If a loader is found, we need to return
238
+ # our own loader which will then in turn call the
239
+ # real loader to import the module and invoke the
240
+ # post import hooks.
241
+
242
+ loader = getattr(find_spec(fullname), "loader", None)
243
+
244
+ if loader and not isinstance(loader, _ImportHookChainedLoader):
245
+ return _ImportHookChainedLoader(loader)
246
+
247
+ finally:
248
+ del self.in_progress[fullname]
249
+
250
+ def find_spec(self, fullname, path=None, target=None):
251
+ # Since Python 3.4, you are meant to implement find_spec() method
252
+ # instead of find_module() and since Python 3.10 you get deprecation
253
+ # warnings if you don't define find_spec().
254
+
255
+ with _post_import_hooks_lock:
256
+ # If the module being imported is not one we have registered
257
+ # post import hooks for, we can return immediately. We will
258
+ # take no further part in the importing of this module.
259
+
260
+ if fullname not in _post_import_hooks:
261
+ return None
262
+
263
+ # When we are interested in a specific module, we will call back
264
+ # into the import system a second time to defer to the import
265
+ # finder that is supposed to handle the importing of the module.
266
+ # We set an in progress flag for the target module so that on
267
+ # the second time through we don't trigger another call back
268
+ # into the import system and cause a infinite loop.
269
+
270
+ if fullname in self.in_progress:
271
+ return None
272
+
273
+ self.in_progress[fullname] = True
274
+
275
+ # Now call back into the import system again.
276
+
277
+ try:
278
+ # This should only be Python 3 so find_spec() should always
279
+ # exist so don't need to check.
280
+
281
+ spec = find_spec(fullname)
282
+ loader = getattr(spec, "loader", None)
283
+
284
+ if loader and not isinstance(loader, _ImportHookChainedLoader):
285
+ spec.loader = _ImportHookChainedLoader(loader)
286
+
287
+ return spec
288
+
289
+ finally:
290
+ del self.in_progress[fullname]
291
+
292
+
293
+ # Decorator for marking that a function should be called as a post
294
+ # import hook when the target module is imported.
295
+
296
+
297
+ def when_imported(name):
298
+ """
299
+ Returns a decorator that registers the decorated function as a post import
300
+ hook for the module specified by `name`. The function will be called once
301
+ the module with the specified name is imported, and will be passed the
302
+ module as argument. If the module is already imported, the function will
303
+ be called immediately.
304
+ """
305
+
306
+ def register(hook):
307
+ register_post_import_hook(hook, name)
308
+ return hook
309
+
310
+ return register
wrapt/patches.py ADDED
@@ -0,0 +1,284 @@
1
+ """Utilities for monkey patching and wrapping object attributes."""
2
+
3
+ import inspect
4
+ import sys
5
+
6
+ from .__wrapt__ import FunctionWrapper
7
+ from .importer import register_post_import_hook
8
+
9
+ # Helper functions for applying wrappers to existing functions.
10
+
11
+
12
+ def resolve_path(target, name):
13
+ """
14
+ Resolves the dotted path supplied as `name` to an attribute on a target
15
+ object. The `target` can be a module, class, or instance of a class. If the
16
+ `target` argument is a string, it is assumed to be the name of a module,
17
+ which will be imported if necessary and then used as the target object.
18
+ Returns a tuple containing the parent object holding the attribute lookup
19
+ resolved to, the attribute name (path prefix removed if present), and the
20
+ original attribute value.
21
+ """
22
+
23
+ if isinstance(target, str):
24
+ __import__(target)
25
+ target = sys.modules[target]
26
+
27
+ parent = target
28
+
29
+ path = name.split(".")
30
+ attribute = path[0]
31
+
32
+ # We can't just always use getattr() because in doing
33
+ # that on a class it will cause binding to occur which
34
+ # will complicate things later and cause some things not
35
+ # to work. For the case of a class we therefore access
36
+ # the __dict__ directly. To cope though with the wrong
37
+ # class being given to us, or a method being moved into
38
+ # a base class, we need to walk the class hierarchy to
39
+ # work out exactly which __dict__ the method was defined
40
+ # in, as accessing it from __dict__ will fail if it was
41
+ # not actually on the class given. Fallback to using
42
+ # getattr() if we can't find it. If it truly doesn't
43
+ # exist, then that will fail.
44
+
45
+ def lookup_attribute(parent, attribute):
46
+ if inspect.isclass(parent):
47
+ for cls in inspect.getmro(parent):
48
+ if attribute in vars(cls):
49
+ return vars(cls)[attribute]
50
+ else:
51
+ return getattr(parent, attribute)
52
+ else:
53
+ return getattr(parent, attribute)
54
+
55
+ original = lookup_attribute(parent, attribute)
56
+
57
+ for attribute in path[1:]:
58
+ parent = original
59
+ original = lookup_attribute(parent, attribute)
60
+
61
+ return (parent, attribute, original)
62
+
63
+
64
+ def apply_patch(parent, attribute, replacement):
65
+ """
66
+ Convenience function for applying a patch to an attribute. This maps to
67
+ the standard setattr() function.
68
+ """
69
+
70
+ setattr(parent, attribute, replacement)
71
+
72
+
73
+ def wrap_object(target, name, factory, args=(), kwargs=None):
74
+ """
75
+ Wraps an object which is the attribute of a target object with a wrapper
76
+ object created by the `factory` function. The `target` can be a module,
77
+ class, or instance of a class. In the special case of `target` being a
78
+ string, it is assumed to be the name of a module, with the module being
79
+ imported if necessary and then used as the target object. The `name` is a
80
+ string representing the dotted path to the attribute. The `factory` function
81
+ should accept the original object and may accept additional positional and
82
+ keyword arguments which will be set by unpacking input arguments using
83
+ `*args` and `**kwargs` calling conventions. The factory function should
84
+ return a new object that will replace the original object.
85
+ """
86
+
87
+ if kwargs is None:
88
+ kwargs = {}
89
+
90
+ (parent, attribute, original) = resolve_path(target, name)
91
+ wrapper = factory(original, *args, **kwargs)
92
+ apply_patch(parent, attribute, wrapper)
93
+
94
+ return wrapper
95
+
96
+
97
+ # Function for applying a proxy object to an attribute of a class
98
+ # instance. The wrapper works by defining an attribute of the same name
99
+ # on the class which is a descriptor and which intercepts access to the
100
+ # instance attribute. Note that this cannot be used on attributes which
101
+ # are themselves defined by a property object.
102
+
103
+
104
+ class AttributeWrapper:
105
+ """A descriptor that intercepts access to an instance attribute to apply
106
+ a wrapper factory."""
107
+
108
+ def __init__(self, attribute, factory, args, kwargs):
109
+ self.attribute = attribute
110
+ self.factory = factory
111
+ self.args = args
112
+ self.kwargs = kwargs
113
+
114
+ def __get__(self, instance, owner):
115
+ value = instance.__dict__[self.attribute]
116
+ return self.factory(value, *self.args, **self.kwargs)
117
+
118
+ def __set__(self, instance, value):
119
+ instance.__dict__[self.attribute] = value
120
+
121
+ def __delete__(self, instance):
122
+ del instance.__dict__[self.attribute]
123
+
124
+
125
+ def wrap_object_attribute(module, name, factory, args=(), kwargs=None):
126
+ """
127
+ Wraps an object which is the attribute of a class instance with a wrapper
128
+ object created by the `factory` function. It does this by patching the
129
+ class, not the instance, with a descriptor that intercepts access to the
130
+ instance attribute. The `module` can be a module, class, or instance of a
131
+ class. In the special case of `module` being a string, it is assumed to be
132
+ the name of a module, with the module being imported if necessary and then
133
+ used as the target object. The `name` is a string representing the dotted
134
+ path to the attribute. The `factory` function should accept the original
135
+ object and may accept additional positional and keyword arguments which will
136
+ be set by unpacking input arguments using `*args` and `**kwargs` calling
137
+ conventions. The factory function should return a new object that will
138
+ replace the original object.
139
+ """
140
+
141
+ if kwargs is None:
142
+ kwargs = {}
143
+
144
+ path, attribute = name.rsplit(".", 1)
145
+ parent = resolve_path(module, path)[2]
146
+ wrapper = AttributeWrapper(attribute, factory, args, kwargs)
147
+ apply_patch(parent, attribute, wrapper)
148
+ return wrapper
149
+
150
+
151
+ # Functions for creating a simple decorator using a FunctionWrapper,
152
+ # plus short cut functions for applying wrappers to functions. These are
153
+ # for use when doing monkey patching. For a more featured way of
154
+ # creating decorators see the decorator decorator instead.
155
+
156
+
157
+ def function_wrapper(wrapper):
158
+ """
159
+ Creates a decorator for wrapping a function with a `wrapper` function.
160
+ The decorator which is returned may also be applied to any other callable
161
+ objects such as lambda functions, methods, classmethods, and staticmethods,
162
+ or objects which implement the `__call__()` method. The `wrapper` function
163
+ should accept the `wrapped` function, `instance`, `args`, and `kwargs`,
164
+ arguments and return the result of calling the wrapped function or some
165
+ other appropriate value.
166
+ """
167
+
168
+ def _wrapper(wrapped, instance, args, kwargs):
169
+ target_wrapped = args[0]
170
+ if instance is None:
171
+ target_wrapper = wrapper
172
+ elif inspect.isclass(instance):
173
+ target_wrapper = wrapper.__get__(None, instance)
174
+ else:
175
+ target_wrapper = wrapper.__get__(instance, type(instance))
176
+ return FunctionWrapper(target_wrapped, target_wrapper)
177
+
178
+ return FunctionWrapper(wrapper, _wrapper)
179
+
180
+
181
+ def wrap_function_wrapper(target, name, wrapper):
182
+ """
183
+ Wraps a function which is the attribute of a target object with a `wrapper`
184
+ function. The `target` can be a module, class, or instance of a class. In
185
+ the special case of `target` being a string, it is assumed to be the name
186
+ of a module, with the module being imported if necessary. If the `target`
187
+ is a string with a trailing ``?``, the wrapping will be deferred until the
188
+ module is imported. If the module is already imported, the wrapping will be
189
+ applied immediately. The `name` is a string representing the dotted path to
190
+ the attribute. The `wrapper` function should accept the `wrapped` function,
191
+ `instance`, `args`, and `kwargs` arguments, and would return the result of
192
+ calling the wrapped attribute or some other appropriate value. Returns the
193
+ wrapped target function if the wrapping was applied immediately, or ``None``
194
+ if the wrapping was deferred.
195
+ """
196
+
197
+ if isinstance(target, str) and target.endswith("?"):
198
+ target = target[:-1]
199
+
200
+ if target in sys.modules:
201
+ return wrap_object(sys.modules[target], name, FunctionWrapper, (wrapper,))
202
+
203
+ def callback(module):
204
+ wrap_object(module, name, FunctionWrapper, (wrapper,))
205
+
206
+ register_post_import_hook(callback, target)
207
+ return None
208
+
209
+ return wrap_object(target, name, FunctionWrapper, (wrapper,))
210
+
211
+
212
+ def patch_function_wrapper(target, name, enabled=None):
213
+ """
214
+ Creates a decorator which can be applied to a wrapper function, where the
215
+ wrapper function will be used to wrap a function which is the attribute of
216
+ a target object. The decorator returns the original wrapper function. The
217
+ `target` can be a module, class, or instance of a class. In the special case
218
+ of `target` being a string, it is assumed to be the name of a module, with
219
+ the module being imported if necessary. If the `target` is a string with a
220
+ trailing ``?``, the wrapping will be deferred until the module is imported.
221
+ If the module is already imported, the wrapping will be applied immediately.
222
+ The `name` is a string representing the dotted path to the attribute. The
223
+ `enabled` argument can be a boolean or a callable that returns a boolean.
224
+ When a callable is provided, it will be called each time the wrapper is
225
+ invoked to determine if the wrapper function should be executed or whether
226
+ the wrapped function should be called directly. If `enabled` is not
227
+ provided, the wrapper is enabled by default.
228
+ """
229
+
230
+ def _wrapper(wrapper):
231
+ if isinstance(target, str) and target.endswith("?"):
232
+ _target = target[:-1]
233
+
234
+ if _target in sys.modules:
235
+ wrap_object(
236
+ sys.modules[_target], name, FunctionWrapper, (wrapper, enabled)
237
+ )
238
+ return wrapper
239
+
240
+ def callback(module):
241
+ wrap_object(module, name, FunctionWrapper, (wrapper, enabled))
242
+
243
+ register_post_import_hook(callback, _target)
244
+ return wrapper
245
+
246
+ wrap_object(target, name, FunctionWrapper, (wrapper, enabled))
247
+ return wrapper
248
+
249
+ return _wrapper
250
+
251
+
252
+ def transient_function_wrapper(target, name):
253
+ """Creates a decorator that patches a target function with a wrapper
254
+ function, but only for the duration of the call that the decorator was
255
+ applied to. The `target` can be a module, class, or instance of a class.
256
+ In the special case of `target` being a string, it is assumed to be the name
257
+ of a module, with the module being imported if necessary. The `name` is a
258
+ string representing the dotted path to the attribute.
259
+ """
260
+
261
+ def _decorator(wrapper):
262
+ def _wrapper(wrapped, instance, args, kwargs):
263
+ target_wrapped = args[0]
264
+ if instance is None:
265
+ target_wrapper = wrapper
266
+ elif inspect.isclass(instance):
267
+ target_wrapper = wrapper.__get__(None, instance)
268
+ else:
269
+ target_wrapper = wrapper.__get__(instance, type(instance))
270
+
271
+ def _execute(wrapped, instance, args, kwargs):
272
+ (parent, attribute, original) = resolve_path(target, name)
273
+ replacement = FunctionWrapper(original, target_wrapper)
274
+ setattr(parent, attribute, replacement)
275
+ try:
276
+ return wrapped(*args, **kwargs)
277
+ finally:
278
+ setattr(parent, attribute, original)
279
+
280
+ return FunctionWrapper(target_wrapped, _execute)
281
+
282
+ return FunctionWrapper(wrapper, _wrapper)
283
+
284
+ return _decorator