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/decorators.py ADDED
@@ -0,0 +1,480 @@
1
+ """This module implements decorators for implementing other decorators
2
+ as well as some commonly used decorators.
3
+
4
+ """
5
+
6
+ from functools import partial
7
+ from inspect import isclass, signature
8
+
9
+ from .__wrapt__ import (
10
+ BaseObjectProxy,
11
+ BoundFunctionWrapper,
12
+ CallableObjectProxy,
13
+ FunctionWrapper,
14
+ )
15
+ from .arguments import formatargspec
16
+
17
+ # Adapter wrapper for the wrapped function which will overlay certain
18
+ # properties from the adapter function onto the wrapped function so that
19
+ # functions such as inspect.getfullargspec(), inspect.signature() and
20
+ # inspect.getsource() return the correct results one would expect.
21
+
22
+
23
+ class _AdapterFunctionCode(CallableObjectProxy):
24
+
25
+ def __init__(self, wrapped_code, adapter_code):
26
+ # Explicit class in super() is used because the proxy overrides
27
+ # __class__ and MRO-related methods to delegate to the wrapped
28
+ # object, which can interfere with bare super().
29
+ super(_AdapterFunctionCode, self).__init__(wrapped_code)
30
+ self._self_adapter_code = adapter_code
31
+
32
+ @property
33
+ def co_argcount(self):
34
+ return self._self_adapter_code.co_argcount
35
+
36
+ @property
37
+ def co_code(self):
38
+ return self._self_adapter_code.co_code
39
+
40
+ @property
41
+ def co_flags(self):
42
+ return self._self_adapter_code.co_flags
43
+
44
+ @property
45
+ def co_kwonlyargcount(self):
46
+ return self._self_adapter_code.co_kwonlyargcount
47
+
48
+ @property
49
+ def co_varnames(self):
50
+ return self._self_adapter_code.co_varnames
51
+
52
+
53
+ class _AdapterFunctionSurrogate(CallableObjectProxy):
54
+
55
+ def __init__(self, wrapped, adapter):
56
+ # Explicit class in super() is used because the proxy overrides
57
+ # __class__ and MRO-related methods to delegate to the wrapped
58
+ # object, which can interfere with bare super().
59
+ super(_AdapterFunctionSurrogate, self).__init__(wrapped)
60
+ self._self_adapter = adapter
61
+
62
+ @property
63
+ def __code__(self):
64
+ return _AdapterFunctionCode(
65
+ self.__wrapped__.__code__, self._self_adapter.__code__
66
+ )
67
+
68
+ @property
69
+ def __defaults__(self):
70
+ return self._self_adapter.__defaults__
71
+
72
+ @property
73
+ def __kwdefaults__(self):
74
+ return self._self_adapter.__kwdefaults__
75
+
76
+ @property
77
+ def __signature__(self):
78
+ return signature(self._self_adapter)
79
+
80
+
81
+ class _BoundAdapterFunctionWrapper(BoundFunctionWrapper):
82
+
83
+ @property
84
+ def __func__(self):
85
+ return _AdapterFunctionSurrogate(
86
+ self.__wrapped__.__func__, self._self_parent._self_adapter
87
+ )
88
+
89
+ @property
90
+ def __signature__(self):
91
+ return signature(self._self_parent._self_adapter)
92
+
93
+
94
+ class _AdapterFunctionWrapper(FunctionWrapper):
95
+
96
+ __bound_function_wrapper__ = _BoundAdapterFunctionWrapper
97
+
98
+ def __init__(self, *args, **kwargs):
99
+ adapter = kwargs.pop("adapter")
100
+ # Explicit class in super() is used because the proxy overrides
101
+ # __class__ and MRO-related methods to delegate to the wrapped
102
+ # object, which can interfere with bare super().
103
+ super(_AdapterFunctionWrapper, self).__init__(*args, **kwargs)
104
+ self._self_surrogate = _AdapterFunctionSurrogate(self.__wrapped__, adapter)
105
+ self._self_adapter = adapter
106
+
107
+ @property
108
+ def __code__(self):
109
+ return self._self_surrogate.__code__
110
+
111
+ @property
112
+ def __defaults__(self):
113
+ return self._self_surrogate.__defaults__
114
+
115
+ @property
116
+ def __kwdefaults__(self):
117
+ return self._self_surrogate.__kwdefaults__
118
+
119
+ @property
120
+ def __signature__(self):
121
+ return self._self_surrogate.__signature__
122
+
123
+
124
+ class AdapterFactory:
125
+ def __call__(self, wrapped):
126
+ raise NotImplementedError()
127
+
128
+
129
+ class _DelegatedAdapterFactory(AdapterFactory):
130
+ def __init__(self, factory):
131
+ # Explicit class in super() for consistency with proxy subclasses.
132
+ super(_DelegatedAdapterFactory, self).__init__()
133
+ self.factory = factory
134
+
135
+ def __call__(self, wrapped):
136
+ return self.factory(wrapped)
137
+
138
+
139
+ adapter_factory = _DelegatedAdapterFactory
140
+
141
+ # Decorator for creating other decorators. This decorator and the
142
+ # wrappers which they use are designed to properly preserve any name
143
+ # attributes, function signatures etc, in addition to the wrappers
144
+ # themselves acting like a transparent proxy for the original wrapped
145
+ # function so the wrapper is effectively indistinguishable from the
146
+ # original wrapped function.
147
+
148
+
149
+ def decorator(wrapper=None, /, *, enabled=None, adapter=None, proxy=FunctionWrapper):
150
+ """
151
+ The decorator should be supplied with a single positional argument
152
+ which is the `wrapper` function to be used to implement the
153
+ decorator. This may be preceded by a step whereby the keyword
154
+ arguments are supplied to customise the behaviour of the
155
+ decorator. The `adapter` argument is used to optionally denote a
156
+ separate function which is notionally used by an adapter
157
+ decorator. In that case parts of the function `__code__` and
158
+ `__defaults__` attributes are used from the adapter function
159
+ rather than those of the wrapped function. This allows for the
160
+ argument specification from `inspect.getfullargspec()` and similar
161
+ functions to be overridden with a prototype for a different
162
+ function than what was wrapped. The `enabled` argument provides a
163
+ way to enable/disable the use of the decorator. If the type of
164
+ `enabled` is a boolean, then it is evaluated immediately and the
165
+ wrapper not even applied if it is `False`. If not a boolean, it will
166
+ be evaluated when the wrapper is called for an unbound wrapper,
167
+ and when binding occurs for a bound wrapper. When being evaluated,
168
+ if `enabled` is callable it will be called to obtain the value to
169
+ be checked. If `False`, the wrapper will not be called and instead
170
+ the original wrapped function will be called directly instead.
171
+ The `proxy` argument provides a way of passing a custom version of
172
+ the `FunctionWrapper` class used in decorating the function.
173
+ """
174
+
175
+ if wrapper is not None:
176
+ # Helper function for creating wrapper of the appropriate
177
+ # time when we need it down below.
178
+
179
+ def _build(wrapped, wrapper, enabled=None, adapter=None):
180
+ if adapter:
181
+ if isinstance(adapter, AdapterFactory):
182
+ adapter = adapter(wrapped)
183
+
184
+ if not callable(adapter):
185
+ ns = {}
186
+
187
+ # Check if the signature argument specification has
188
+ # annotations. If it does then we need to remember
189
+ # it but also drop it when attempting to manufacture
190
+ # a standin adapter function. This is necessary else
191
+ # it will try and look up any types referenced in
192
+ # the annotations in the empty namespace we use,
193
+ # which will fail.
194
+
195
+ annotations = {}
196
+
197
+ if not isinstance(adapter, str):
198
+ if len(adapter) == 7:
199
+ annotations = adapter[-1]
200
+ adapter = adapter[:-1]
201
+ adapter = formatargspec(*adapter)
202
+
203
+ exec(f"def adapter{adapter}: pass", ns, ns)
204
+ adapter = ns["adapter"]
205
+
206
+ # Override the annotations for the manufactured
207
+ # adapter function so they match the original
208
+ # adapter signature argument specification.
209
+
210
+ if annotations:
211
+ adapter.__annotations__ = annotations
212
+
213
+ return _AdapterFunctionWrapper(
214
+ wrapped=wrapped, wrapper=wrapper, enabled=enabled, adapter=adapter
215
+ )
216
+
217
+ return proxy(wrapped=wrapped, wrapper=wrapper, enabled=enabled)
218
+
219
+ # The wrapper has been provided so return the final decorator.
220
+ # The decorator is itself one of our function wrappers so we
221
+ # can determine when it is applied to functions, instance methods
222
+ # or class methods. This allows us to bind the instance or class
223
+ # method so the appropriate self or cls attribute is supplied
224
+ # when it is finally called.
225
+
226
+ def _wrapper(wrapped, instance, args, kwargs):
227
+ # We first check for the case where the decorator was applied
228
+ # to a class type.
229
+ #
230
+ # @decorator
231
+ # class mydecoratorclass:
232
+ # def __init__(self, arg=None):
233
+ # self.arg = arg
234
+ # def __call__(self, wrapped, instance, args, kwargs):
235
+ # return wrapped(*args, **kwargs)
236
+ #
237
+ # @mydecoratorclass(arg=1)
238
+ # def function():
239
+ # pass
240
+ #
241
+ # In this case an instance of the class is to be used as the
242
+ # decorator wrapper function. If args was empty at this point,
243
+ # then it means that there were optional keyword arguments
244
+ # supplied to be used when creating an instance of the class
245
+ # to be used as the wrapper function.
246
+
247
+ if instance is None and isclass(wrapped) and not args:
248
+ # We still need to be passed the target function to be
249
+ # wrapped as yet, so we need to return a further function
250
+ # to be able to capture it.
251
+
252
+ def _capture(target_wrapped):
253
+ # Now have the target function to be wrapped and need
254
+ # to create an instance of the class which is to act
255
+ # as the decorator wrapper function. Before we do that,
256
+ # we need to first check that use of the decorator
257
+ # hadn't been disabled by a simple boolean. If it was,
258
+ # the target function to be wrapped is returned instead.
259
+
260
+ _enabled = enabled
261
+ if type(_enabled) is bool:
262
+ if not _enabled:
263
+ return target_wrapped
264
+ _enabled = None
265
+
266
+ # Now create an instance of the class which is to act
267
+ # as the decorator wrapper function. Any arguments had
268
+ # to be supplied as keyword only arguments so that is
269
+ # all we pass when creating it.
270
+
271
+ target_wrapper = wrapped(**kwargs)
272
+
273
+ # Finally build the wrapper itself and return it.
274
+
275
+ return _build(target_wrapped, target_wrapper, _enabled, adapter)
276
+
277
+ return _capture
278
+
279
+ # We should always have the target function to be wrapped at
280
+ # this point as the first (and only) value in args.
281
+
282
+ target_wrapped = args[0]
283
+
284
+ # Need to now check that use of the decorator hadn't been
285
+ # disabled by a simple boolean. If it was, then target
286
+ # function to be wrapped is returned instead.
287
+
288
+ _enabled = enabled
289
+ if type(_enabled) is bool:
290
+ if not _enabled:
291
+ return target_wrapped
292
+ _enabled = None
293
+
294
+ # We now need to build the wrapper, but there are a couple of
295
+ # different cases we need to consider.
296
+
297
+ if instance is None:
298
+ if isclass(wrapped):
299
+ # In this case the decorator was applied to a class
300
+ # type but optional keyword arguments were not supplied
301
+ # for initialising an instance of the class to be used
302
+ # as the decorator wrapper function.
303
+ #
304
+ # @decorator
305
+ # class mydecoratorclass:
306
+ # def __init__(self, arg=None):
307
+ # self.arg = arg
308
+ # def __call__(self, wrapped, instance,
309
+ # args, kwargs):
310
+ # return wrapped(*args, **kwargs)
311
+ #
312
+ # @mydecoratorclass
313
+ # def function():
314
+ # pass
315
+ #
316
+ # We still need to create an instance of the class to
317
+ # be used as the decorator wrapper function, but no
318
+ # arguments are pass.
319
+
320
+ target_wrapper = wrapped()
321
+
322
+ else:
323
+ # In this case the decorator was applied to a normal
324
+ # function, or possibly a static method of a class.
325
+ #
326
+ # @decorator
327
+ # def mydecoratorfuntion(wrapped, instance,
328
+ # args, kwargs):
329
+ # return wrapped(*args, **kwargs)
330
+ #
331
+ # @mydecoratorfunction
332
+ # def function():
333
+ # pass
334
+ #
335
+ # That normal function becomes the decorator wrapper
336
+ # function.
337
+
338
+ target_wrapper = wrapper
339
+
340
+ else:
341
+ if isclass(instance):
342
+ # In this case the decorator was applied to a class
343
+ # method.
344
+ #
345
+ # class myclass:
346
+ # @decorator
347
+ # @classmethod
348
+ # def decoratorclassmethod(cls, wrapped,
349
+ # instance, args, kwargs):
350
+ # return wrapped(*args, **kwargs)
351
+ #
352
+ # instance = myclass()
353
+ #
354
+ # @instance.decoratorclassmethod
355
+ # def function():
356
+ # pass
357
+ #
358
+ # This one is a bit strange because binding was actually
359
+ # performed on the wrapper created by our decorator
360
+ # factory. We need to apply that binding to the decorator
361
+ # wrapper function that the decorator factory
362
+ # was applied to.
363
+
364
+ target_wrapper = wrapper.__get__(None, instance)
365
+
366
+ else:
367
+ # In this case the decorator was applied to an instance
368
+ # method.
369
+ #
370
+ # class myclass:
371
+ # @decorator
372
+ # def decoratorclassmethod(self, wrapped,
373
+ # instance, args, kwargs):
374
+ # return wrapped(*args, **kwargs)
375
+ #
376
+ # instance = myclass()
377
+ #
378
+ # @instance.decoratorclassmethod
379
+ # def function():
380
+ # pass
381
+ #
382
+ # This one is a bit strange because binding was actually
383
+ # performed on the wrapper created by our decorator
384
+ # factory. We need to apply that binding to the decorator
385
+ # wrapper function that the decorator factory
386
+ # was applied to.
387
+
388
+ target_wrapper = wrapper.__get__(instance, type(instance))
389
+
390
+ # Finally build the wrapper itself and return it.
391
+
392
+ return _build(target_wrapped, target_wrapper, _enabled, adapter)
393
+
394
+ # We first return our magic function wrapper here so we can
395
+ # determine in what context the decorator factory was used. In
396
+ # other words, it is itself a universal decorator. The decorator
397
+ # function is used as the adapter so that linters see a signature
398
+ # corresponding to the decorator and not the wrapper it is being
399
+ # applied to.
400
+
401
+ return _build(wrapper, _wrapper, adapter=decorator)
402
+
403
+ else:
404
+ # The wrapper still has not been provided, so we are just
405
+ # collecting the optional keyword arguments. Return the
406
+ # decorator again wrapped in a partial using the collected
407
+ # arguments.
408
+
409
+ return partial(decorator, enabled=enabled, adapter=adapter, proxy=proxy)
410
+
411
+
412
+ # Descriptor decorator for automatically binding state to a wrapper.
413
+ # When applied to a method decorated with function_wrapper or decorator,
414
+ # it intercepts descriptor access so that when the method is accessed
415
+ # via an instance, the instance is automatically attached to the
416
+ # resulting wrapper using __self_setattr__. This is useful when you
417
+ # want the wrapper to carry a reference back to the object that owns
418
+ # the wrapper factory method, making state accessible through the
419
+ # decorated function without manual setup.
420
+
421
+
422
+ class _StateBindingWrapper(BaseObjectProxy):
423
+ """A descriptor decorator that binds the owner instance to wrappers
424
+ produced by a wrapper factory method.
425
+
426
+ When applied on top of a method decorated with ``function_wrapper``
427
+ or ``decorator``, it intercepts the descriptor ``__get__`` so that
428
+ when the method is accessed through an instance, the owner instance
429
+ is automatically attached as an attribute on the resulting wrapper
430
+ via ``__self_setattr__``.
431
+
432
+ The *name* keyword argument controls the attribute name under which
433
+ the owner instance is stored on the wrapper (default ``"state"``).
434
+ """
435
+
436
+ def __init__(self, *, name="state"):
437
+ # Initialise the proxy with a placeholder. The actual wrapper
438
+ # factory is set later when __call__ is invoked as a decorator.
439
+
440
+ super().__init__(None)
441
+
442
+ self._self_name = name
443
+
444
+ def __call__(self, wrapper_factory):
445
+ # Called when used as a decorator, receiving the wrapper factory
446
+ # (the function_wrapper or decorator-decorated method) to wrap.
447
+
448
+ self.__wrapped__ = wrapper_factory
449
+
450
+ return self
451
+
452
+ def __get__(self, instance, owner):
453
+ # When accessed via the class rather than an instance, return
454
+ # the descriptor itself unchanged. This preserves introspection
455
+ # of the underlying wrapper factory via the object proxy.
456
+
457
+ if instance is None:
458
+ return self
459
+
460
+ # Bind the underlying wrapper factory to the instance so it
461
+ # receives the correct self/cls when called.
462
+
463
+ wrapper_factory = self.__wrapped__.__get__(instance, owner)
464
+
465
+ name = self._self_name
466
+
467
+ def _bind(func):
468
+ wrapper = wrapper_factory(func)
469
+
470
+ # Attach the owner instance to the wrapper so it can be
471
+ # accessed as an attribute of the decorated function.
472
+
473
+ wrapper.__self_setattr__(name, instance)
474
+
475
+ return wrapper
476
+
477
+ return _bind
478
+
479
+
480
+ bind_state_to_wrapper = _StateBindingWrapper