Debian Codegraph @

lib/ansible/_internal/_wrapt.py

raw
1 # Copyright (c) 2013-2023, Graham Dumpleton
2 # All rights reserved.
3 #
4 # Redistribution and use in source and binary forms, with or without
5 # modification, are permitted provided that the following conditions are met:
6 #
7 # * Redistributions of source code must retain the above copyright notice, this
8 # list of conditions and the following disclaimer.
9 #
10 # * Redistributions in binary form must reproduce the above copyright notice,
11 # this list of conditions and the following disclaimer in the documentation
12 # and/or other materials provided with the distribution.
13 #
14 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
15 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
18 # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
19 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
20 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
21 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
22 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
23 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
24 # POSSIBILITY OF SUCH DAMAGE.
25
26 # copied from https://github.com/GrahamDumpleton/wrapt/blob/1.17.2/src/wrapt/wrappers.py
27
28 # LOCAL PATCHES:
29 # - disabled optional relative import of the _wrappers C extension; we shouldn't need it
30
31 from __future__ import annotations
32
33 # The following makes it easier for us to script updates of the bundled code
34 _BUNDLED_METADATA = {"pypi_name": "wrapt", "version": "1.17.2"}
35
36 import sys
37 import operator
38 import inspect
39
40 PY2 = sys.version_info[0] == 2
41
42 if PY2:
43 string_types = basestring,
44 else:
45 string_types = str,
46
47 def with_metaclass(meta, *bases):
48 """Create a base class with a metaclass."""
49 return meta("NewBase", bases, {})
50
51 class _ObjectProxyMethods(object):
52
53 # We use properties to override the values of __module__ and
54 # __doc__. If we add these in ObjectProxy, the derived class
55 # __dict__ will still be setup to have string variants of these
56 # attributes and the rules of descriptors means that they appear to
57 # take precedence over the properties in the base class. To avoid
58 # that, we copy the properties into the derived class type itself
59 # via a meta class. In that way the properties will always take
60 # precedence.
61
62 @property
63 def __module__(self):
64 return self.__wrapped__.__module__
65
66 @__module__.setter
67 def __module__(self, value):
68 self.__wrapped__.__module__ = value
69
70 @property
71 def __doc__(self):
72 return self.__wrapped__.__doc__
73
74 @__doc__.setter
75 def __doc__(self, value):
76 self.__wrapped__.__doc__ = value
77
78 # We similar use a property for __dict__. We need __dict__ to be
79 # explicit to ensure that vars() works as expected.
80
81 @property
82 def __dict__(self):
83 return self.__wrapped__.__dict__
84
85 # Need to also propagate the special __weakref__ attribute for case
86 # where decorating classes which will define this. If do not define
87 # it and use a function like inspect.getmembers() on a decorator
88 # class it will fail. This can't be in the derived classes.
89
90 @property
91 def __weakref__(self):
92 return self.__wrapped__.__weakref__
93
94 class _ObjectProxyMetaType(type):
95 def __new__(cls, name, bases, dictionary):
96 # Copy our special properties into the class so that they
97 # always take precedence over attributes of the same name added
98 # during construction of a derived class. This is to save
99 # duplicating the implementation for them in all derived classes.
100
101 dictionary.update(vars(_ObjectProxyMethods))
102
103 return type.__new__(cls, name, bases, dictionary)
104
105 class ObjectProxy(with_metaclass(_ObjectProxyMetaType)):
106
107 __slots__ = '__wrapped__'
108
109 def __init__(self, wrapped):
110 object.__setattr__(self, '__wrapped__', wrapped)
111
112 # Python 3.2+ has the __qualname__ attribute, but it does not
113 # allow it to be overridden using a property and it must instead
114 # be an actual string object instead.
115
116 try:
117 object.__setattr__(self, '__qualname__', wrapped.__qualname__)
118 except AttributeError:
119 pass
120
121 # Python 3.10 onwards also does not allow itself to be overridden
122 # using a property and it must instead be set explicitly.
123
124 try:
125 object.__setattr__(self, '__annotations__', wrapped.__annotations__)
126 except AttributeError:
127 pass
128
129 def __self_setattr__(self, name, value):
130 object.__setattr__(self, name, value)
131
132 @property
133 def __name__(self):
134 return self.__wrapped__.__name__
135
136 @__name__.setter
137 def __name__(self, value):
138 self.__wrapped__.__name__ = value
139
140 @property
141 def __class__(self):
142 return self.__wrapped__.__class__
143
144 @__class__.setter
145 def __class__(self, value):
146 self.__wrapped__.__class__ = value
147
148 def __dir__(self):
149 return dir(self.__wrapped__)
150
151 def __str__(self):
152 return str(self.__wrapped__)
153
154 if not PY2:
155 def __bytes__(self):
156 return bytes(self.__wrapped__)
157
158 def __repr__(self):
159 return '<{} at 0x{:x} for {} at 0x{:x}>'.format(
160 type(self).__name__, id(self),
161 type(self.__wrapped__).__name__,
162 id(self.__wrapped__))
163
164 def __format__(self, format_spec):
165 return format(self.__wrapped__, format_spec)
166
167 def __reversed__(self):
168 return reversed(self.__wrapped__)
169
170 if not PY2:
171 def __round__(self, ndigits=None):
172 return round(self.__wrapped__, ndigits)
173
174 if sys.hexversion >= 0x03070000:
175 def __mro_entries__(self, bases):
176 return (self.__wrapped__,)
177
178 def __lt__(self, other):
179 return self.__wrapped__ < other
180
181 def __le__(self, other):
182 return self.__wrapped__ <= other
183
184 def __eq__(self, other):
185 return self.__wrapped__ == other
186
187 def __ne__(self, other):
188 return self.__wrapped__ != other
189
190 def __gt__(self, other):
191 return self.__wrapped__ > other
192
193 def __ge__(self, other):
194 return self.__wrapped__ >= other
195
196 def __hash__(self):
197 return hash(self.__wrapped__)
198
199 def __nonzero__(self):
200 return bool(self.__wrapped__)
201
202 def __bool__(self):
203 return bool(self.__wrapped__)
204
205 def __setattr__(self, name, value):
206 if name.startswith('_self_'):
207 object.__setattr__(self, name, value)
208
209 elif name == '__wrapped__':
210 object.__setattr__(self, name, value)
211 try:
212 object.__delattr__(self, '__qualname__')
213 except AttributeError:
214 pass
215 try:
216 object.__setattr__(self, '__qualname__', value.__qualname__)
217 except AttributeError:
218 pass
219 try:
220 object.__delattr__(self, '__annotations__')
221 except AttributeError:
222 pass
223 try:
224 object.__setattr__(self, '__annotations__', value.__annotations__)
225 except AttributeError:
226 pass
227
228 elif name == '__qualname__':
229 setattr(self.__wrapped__, name, value)
230 object.__setattr__(self, name, value)
231
232 elif name == '__annotations__':
233 setattr(self.__wrapped__, name, value)
234 object.__setattr__(self, name, value)
235
236 elif hasattr(type(self), name):
237 object.__setattr__(self, name, value)
238
239 else:
240 setattr(self.__wrapped__, name, value)
241
242 def __getattr__(self, name):
243 # If we are being to lookup '__wrapped__' then the
244 # '__init__()' method cannot have been called.
245
246 if name == '__wrapped__':
247 raise ValueError('wrapper has not been initialised')
248
249 return getattr(self.__wrapped__, name)
250
251 def __delattr__(self, name):
252 if name.startswith('_self_'):
253 object.__delattr__(self, name)
254
255 elif name == '__wrapped__':
256 raise TypeError('__wrapped__ must be an object')
257
258 elif name == '__qualname__':
259 object.__delattr__(self, name)
260 delattr(self.__wrapped__, name)
261
262 elif hasattr(type(self), name):
263 object.__delattr__(self, name)
264
265 else:
266 delattr(self.__wrapped__, name)
267
268 def __add__(self, other):
269 return self.__wrapped__ + other
270
271 def __sub__(self, other):
272 return self.__wrapped__ - other
273
274 def __mul__(self, other):
275 return self.__wrapped__ * other
276
277 def __div__(self, other):
278 return operator.div(self.__wrapped__, other)
279
280 def __truediv__(self, other):
281 return operator.truediv(self.__wrapped__, other)
282
283 def __floordiv__(self, other):
284 return self.__wrapped__ // other
285
286 def __mod__(self, other):
287 return self.__wrapped__ % other
288
289 def __divmod__(self, other):
290 return divmod(self.__wrapped__, other)
291
292 def __pow__(self, other, *args):
293 return pow(self.__wrapped__, other, *args)
294
295 def __lshift__(self, other):
296 return self.__wrapped__ << other
297
298 def __rshift__(self, other):
299 return self.__wrapped__ >> other
300
301 def __and__(self, other):
302 return self.__wrapped__ & other
303
304 def __xor__(self, other):
305 return self.__wrapped__ ^ other
306
307 def __or__(self, other):
308 return self.__wrapped__ | other
309
310 def __radd__(self, other):
311 return other + self.__wrapped__
312
313 def __rsub__(self, other):
314 return other - self.__wrapped__
315
316 def __rmul__(self, other):
317 return other * self.__wrapped__
318
319 def __rdiv__(self, other):
320 return operator.div(other, self.__wrapped__)
321
322 def __rtruediv__(self, other):
323 return operator.truediv(other, self.__wrapped__)
324
325 def __rfloordiv__(self, other):
326 return other // self.__wrapped__
327
328 def __rmod__(self, other):
329 return other % self.__wrapped__
330
331 def __rdivmod__(self, other):
332 return divmod(other, self.__wrapped__)
333
334 def __rpow__(self, other, *args):
335 return pow(other, self.__wrapped__, *args)
336
337 def __rlshift__(self, other):
338 return other << self.__wrapped__
339
340 def __rrshift__(self, other):
341 return other >> self.__wrapped__
342
343 def __rand__(self, other):
344 return other & self.__wrapped__
345
346 def __rxor__(self, other):
347 return other ^ self.__wrapped__
348
349 def __ror__(self, other):
350 return other | self.__wrapped__
351
352 def __iadd__(self, other):
353 self.__wrapped__ += other
354 return self
355
356 def __isub__(self, other):
357 self.__wrapped__ -= other
358 return self
359
360 def __imul__(self, other):
361 self.__wrapped__ *= other
362 return self
363
364 def __idiv__(self, other):
365 self.__wrapped__ = operator.idiv(self.__wrapped__, other)
366 return self
367
368 def __itruediv__(self, other):
369 self.__wrapped__ = operator.itruediv(self.__wrapped__, other)
370 return self
371
372 def __ifloordiv__(self, other):
373 self.__wrapped__ //= other
374 return self
375
376 def __imod__(self, other):
377 self.__wrapped__ %= other
378 return self
379
380 def __ipow__(self, other):
381 self.__wrapped__ **= other
382 return self
383
384 def __ilshift__(self, other):
385 self.__wrapped__ <<= other
386 return self
387
388 def __irshift__(self, other):
389 self.__wrapped__ >>= other
390 return self
391
392 def __iand__(self, other):
393 self.__wrapped__ &= other
394 return self
395
396 def __ixor__(self, other):
397 self.__wrapped__ ^= other
398 return self
399
400 def __ior__(self, other):
401 self.__wrapped__ |= other
402 return self
403
404 def __neg__(self):
405 return -self.__wrapped__
406
407 def __pos__(self):
408 return +self.__wrapped__
409
410 def __abs__(self):
411 return abs(self.__wrapped__)
412
413 def __invert__(self):
414 return ~self.__wrapped__
415
416 def __int__(self):
417 return int(self.__wrapped__)
418
419 def __long__(self):
420 return long(self.__wrapped__)
421
422 def __float__(self):
423 return float(self.__wrapped__)
424
425 def __complex__(self):
426 return complex(self.__wrapped__)
427
428 def __oct__(self):
429 return oct(self.__wrapped__)
430
431 def __hex__(self):
432 return hex(self.__wrapped__)
433
434 def __index__(self):
435 return operator.index(self.__wrapped__)
436
437 def __len__(self):
438 return len(self.__wrapped__)
439
440 def __contains__(self, value):
441 return value in self.__wrapped__
442
443 def __getitem__(self, key):
444 return self.__wrapped__[key]
445
446 def __setitem__(self, key, value):
447 self.__wrapped__[key] = value
448
449 def __delitem__(self, key):
450 del self.__wrapped__[key]
451
452 def __getslice__(self, i, j):
453 return self.__wrapped__[i:j]
454
455 def __setslice__(self, i, j, value):
456 self.__wrapped__[i:j] = value
457
458 def __delslice__(self, i, j):
459 del self.__wrapped__[i:j]
460
461 def __enter__(self):
462 return self.__wrapped__.__enter__()
463
464 def __exit__(self, *args, **kwargs):
465 return self.__wrapped__.__exit__(*args, **kwargs)
466
467 def __iter__(self):
468 return iter(self.__wrapped__)
469
470 def __copy__(self):
471 raise NotImplementedError('object proxy must define __copy__()')
472
473 def __deepcopy__(self, memo):
474 raise NotImplementedError('object proxy must define __deepcopy__()')
475
476 def __reduce__(self):
477 raise NotImplementedError(
478 'object proxy must define __reduce__()')
479
480 def __reduce_ex__(self, protocol):
481 raise NotImplementedError(
482 'object proxy must define __reduce_ex__()')
483
484 class CallableObjectProxy(ObjectProxy):
485
486 def __call__(*args, **kwargs):
487 def _unpack_self(self, *args):
488 return self, args
489
490 self, args = _unpack_self(*args)
491
492 return self.__wrapped__(*args, **kwargs)
493
494 class PartialCallableObjectProxy(ObjectProxy):
495
496 def __init__(*args, **kwargs):
497 def _unpack_self(self, *args):
498 return self, args
499
500 self, args = _unpack_self(*args)
501
502 if len(args) < 1:
503 raise TypeError('partial type takes at least one argument')
504
505 wrapped, args = args[0], args[1:]
506
507 if not callable(wrapped):
508 raise TypeError('the first argument must be callable')
509
510 super(PartialCallableObjectProxy, self).__init__(wrapped)
511
512 self._self_args = args
513 self._self_kwargs = kwargs
514
515 def __call__(*args, **kwargs):
516 def _unpack_self(self, *args):
517 return self, args
518
519 self, args = _unpack_self(*args)
520
521 _args = self._self_args + args
522
523 _kwargs = dict(self._self_kwargs)
524 _kwargs.update(kwargs)
525
526 return self.__wrapped__(*_args, **_kwargs)
527
528 class _FunctionWrapperBase(ObjectProxy):
529
530 __slots__ = ('_self_instance', '_self_wrapper', '_self_enabled',
531 '_self_binding', '_self_parent', '_self_owner')
532
533 def __init__(self, wrapped, instance, wrapper, enabled=None,
534 binding='callable', parent=None, owner=None):
535
536 super(_FunctionWrapperBase, self).__init__(wrapped)
537
538 object.__setattr__(self, '_self_instance', instance)
539 object.__setattr__(self, '_self_wrapper', wrapper)
540 object.__setattr__(self, '_self_enabled', enabled)
541 object.__setattr__(self, '_self_binding', binding)
542 object.__setattr__(self, '_self_parent', parent)
543 object.__setattr__(self, '_self_owner', owner)
544
545 def __get__(self, instance, owner):
546 # This method is actually doing double duty for both unbound and bound
547 # derived wrapper classes. It should possibly be broken up and the
548 # distinct functionality moved into the derived classes. Can't do that
549 # straight away due to some legacy code which is relying on it being
550 # here in this base class.
551 #
552 # The distinguishing attribute which determines whether we are being
553 # called in an unbound or bound wrapper is the parent attribute. If
554 # binding has never occurred, then the parent will be None.
555 #
556 # First therefore, is if we are called in an unbound wrapper. In this
557 # case we perform the binding.
558 #
559 # We have two special cases to worry about here. These are where we are
560 # decorating a class or builtin function as neither provide a __get__()
561 # method to call. In this case we simply return self.
562 #
563 # Note that we otherwise still do binding even if instance is None and
564 # accessing an unbound instance method from a class. This is because we
565 # need to be able to later detect that specific case as we will need to
566 # extract the instance from the first argument of those passed in.
567
568 if self._self_parent is None:
569 # Technically can probably just check for existence of __get__ on
570 # the wrapped object, but this is more explicit.
571
572 if self._self_binding == 'builtin':
573 return self
574
575 if self._self_binding == "class":
576 return self
577
578 binder = getattr(self.__wrapped__, '__get__', None)
579
580 if binder is None:
581 return self
582
583 descriptor = binder(instance, owner)
584
585 return self.__bound_function_wrapper__(descriptor, instance,
586 self._self_wrapper, self._self_enabled,
587 self._self_binding, self, owner)
588
589 # Now we have the case of binding occurring a second time on what was
590 # already a bound function. In this case we would usually return
591 # ourselves again. This mirrors what Python does.
592 #
593 # The special case this time is where we were originally bound with an
594 # instance of None and we were likely an instance method. In that case
595 # we rebind against the original wrapped function from the parent again.
596
597 if self._self_instance is None and self._self_binding in ('function', 'instancemethod', 'callable'):
598 descriptor = self._self_parent.__wrapped__.__get__(
599 instance, owner)
600
601 return self._self_parent.__bound_function_wrapper__(
602 descriptor, instance, self._self_wrapper,
603 self._self_enabled, self._self_binding,
604 self._self_parent, owner)
605
606 return self
607
608 def __call__(*args, **kwargs):
609 def _unpack_self(self, *args):
610 return self, args
611
612 self, args = _unpack_self(*args)
613
614 # If enabled has been specified, then evaluate it at this point
615 # and if the wrapper is not to be executed, then simply return
616 # the bound function rather than a bound wrapper for the bound
617 # function. When evaluating enabled, if it is callable we call
618 # it, otherwise we evaluate it as a boolean.
619
620 if self._self_enabled is not None:
621 if callable(self._self_enabled):
622 if not self._self_enabled():
623 return self.__wrapped__(*args, **kwargs)
624 elif not self._self_enabled:
625 return self.__wrapped__(*args, **kwargs)
626
627 # This can occur where initial function wrapper was applied to
628 # a function that was already bound to an instance. In that case
629 # we want to extract the instance from the function and use it.
630
631 if self._self_binding in ('function', 'instancemethod', 'classmethod', 'callable'):
632 if self._self_instance is None:
633 instance = getattr(self.__wrapped__, '__self__', None)
634 if instance is not None:
635 return self._self_wrapper(self.__wrapped__, instance,
636 args, kwargs)
637
638 # This is generally invoked when the wrapped function is being
639 # called as a normal function and is not bound to a class as an
640 # instance method. This is also invoked in the case where the
641 # wrapped function was a method, but this wrapper was in turn
642 # wrapped using the staticmethod decorator.
643
644 return self._self_wrapper(self.__wrapped__, self._self_instance,
645 args, kwargs)
646
647 def __set_name__(self, owner, name):
648 # This is a special method use to supply information to
649 # descriptors about what the name of variable in a class
650 # definition is. Not wanting to add this to ObjectProxy as not
651 # sure of broader implications of doing that. Thus restrict to
652 # FunctionWrapper used by decorators.
653
654 if hasattr(self.__wrapped__, "__set_name__"):
655 self.__wrapped__.__set_name__(owner, name)
656
657 def __instancecheck__(self, instance):
658 # This is a special method used by isinstance() to make checks
659 # instance of the `__wrapped__`.
660 return isinstance(instance, self.__wrapped__)
661
662 def __subclasscheck__(self, subclass):
663 # This is a special method used by issubclass() to make checks
664 # about inheritance of classes. We need to upwrap any object
665 # proxy. Not wanting to add this to ObjectProxy as not sure of
666 # broader implications of doing that. Thus restrict to
667 # FunctionWrapper used by decorators.
668
669 if hasattr(subclass, "__wrapped__"):
670 return issubclass(subclass.__wrapped__, self.__wrapped__)
671 else:
672 return issubclass(subclass, self.__wrapped__)
673
674 class BoundFunctionWrapper(_FunctionWrapperBase):
675
676 def __call__(*args, **kwargs):
677 def _unpack_self(self, *args):
678 return self, args
679
680 self, args = _unpack_self(*args)
681
682 # If enabled has been specified, then evaluate it at this point and if
683 # the wrapper is not to be executed, then simply return the bound
684 # function rather than a bound wrapper for the bound function. When
685 # evaluating enabled, if it is callable we call it, otherwise we
686 # evaluate it as a boolean.
687
688 if self._self_enabled is not None:
689 if callable(self._self_enabled):
690 if not self._self_enabled():
691 return self.__wrapped__(*args, **kwargs)
692 elif not self._self_enabled:
693 return self.__wrapped__(*args, **kwargs)
694
695 # We need to do things different depending on whether we are likely
696 # wrapping an instance method vs a static method or class method.
697
698 if self._self_binding == 'function':
699 if self._self_instance is None and args:
700 instance, newargs = args[0], args[1:]
701 if isinstance(instance, self._self_owner):
702 wrapped = PartialCallableObjectProxy(self.__wrapped__, instance)
703 return self._self_wrapper(wrapped, instance, newargs, kwargs)
704
705 return self._self_wrapper(self.__wrapped__, self._self_instance,
706 args, kwargs)
707
708 elif self._self_binding == 'callable':
709 if self._self_instance is None:
710 # This situation can occur where someone is calling the
711 # instancemethod via the class type and passing the instance as
712 # the first argument. We need to shift the args before making
713 # the call to the wrapper and effectively bind the instance to
714 # the wrapped function using a partial so the wrapper doesn't
715 # see anything as being different.
716
717 if not args:
718 raise TypeError('missing 1 required positional argument')
719
720 instance, args = args[0], args[1:]
721 wrapped = PartialCallableObjectProxy(self.__wrapped__, instance)
722 return self._self_wrapper(wrapped, instance, args, kwargs)
723
724 return self._self_wrapper(self.__wrapped__, self._self_instance,
725 args, kwargs)
726
727 else:
728 # As in this case we would be dealing with a classmethod or
729 # staticmethod, then _self_instance will only tell us whether
730 # when calling the classmethod or staticmethod they did it via an
731 # instance of the class it is bound to and not the case where
732 # done by the class type itself. We thus ignore _self_instance
733 # and use the __self__ attribute of the bound function instead.
734 # For a classmethod, this means instance will be the class type
735 # and for a staticmethod it will be None. This is probably the
736 # more useful thing we can pass through even though we loose
737 # knowledge of whether they were called on the instance vs the
738 # class type, as it reflects what they have available in the
739 # decoratored function.
740
741 instance = getattr(self.__wrapped__, '__self__', None)
742
743 return self._self_wrapper(self.__wrapped__, instance, args,
744 kwargs)
745
746 class FunctionWrapper(_FunctionWrapperBase):
747
748 __bound_function_wrapper__ = BoundFunctionWrapper
749
750 def __init__(self, wrapped, wrapper, enabled=None):
751 # What it is we are wrapping here could be anything. We need to
752 # try and detect specific cases though. In particular, we need
753 # to detect when we are given something that is a method of a
754 # class. Further, we need to know when it is likely an instance
755 # method, as opposed to a class or static method. This can
756 # become problematic though as there isn't strictly a fool proof
757 # method of knowing.
758 #
759 # The situations we could encounter when wrapping a method are:
760 #
761 # 1. The wrapper is being applied as part of a decorator which
762 # is a part of the class definition. In this case what we are
763 # given is the raw unbound function, classmethod or staticmethod
764 # wrapper objects.
765 #
766 # The problem here is that we will not know we are being applied
767 # in the context of the class being set up. This becomes
768 # important later for the case of an instance method, because in
769 # that case we just see it as a raw function and can't
770 # distinguish it from wrapping a normal function outside of
771 # a class context.
772 #
773 # 2. The wrapper is being applied when performing monkey
774 # patching of the class type afterwards and the method to be
775 # wrapped was retrieved direct from the __dict__ of the class
776 # type. This is effectively the same as (1) above.
777 #
778 # 3. The wrapper is being applied when performing monkey
779 # patching of the class type afterwards and the method to be
780 # wrapped was retrieved from the class type. In this case
781 # binding will have been performed where the instance against
782 # which the method is bound will be None at that point.
783 #
784 # This case is a problem because we can no longer tell if the
785 # method was a static method, plus if using Python3, we cannot
786 # tell if it was an instance method as the concept of an
787 # unnbound method no longer exists.
788 #
789 # 4. The wrapper is being applied when performing monkey
790 # patching of an instance of a class. In this case binding will
791 # have been perfomed where the instance was not None.
792 #
793 # This case is a problem because we can no longer tell if the
794 # method was a static method.
795 #
796 # Overall, the best we can do is look at the original type of the
797 # object which was wrapped prior to any binding being done and
798 # see if it is an instance of classmethod or staticmethod. In
799 # the case where other decorators are between us and them, if
800 # they do not propagate the __class__ attribute so that the
801 # isinstance() checks works, then likely this will do the wrong
802 # thing where classmethod and staticmethod are used.
803 #
804 # Since it is likely to be very rare that anyone even puts
805 # decorators around classmethod and staticmethod, likelihood of
806 # that being an issue is very small, so we accept it and suggest
807 # that those other decorators be fixed. It is also only an issue
808 # if a decorator wants to actually do things with the arguments.
809 #
810 # As to not being able to identify static methods properly, we
811 # just hope that that isn't something people are going to want
812 # to wrap, or if they do suggest they do it the correct way by
813 # ensuring that it is decorated in the class definition itself,
814 # or patch it in the __dict__ of the class type.
815 #
816 # So to get the best outcome we can, whenever we aren't sure what
817 # it is, we label it as a 'callable'. If it was already bound and
818 # that is rebound later, we assume that it will be an instance
819 # method and try and cope with the possibility that the 'self'
820 # argument it being passed as an explicit argument and shuffle
821 # the arguments around to extract 'self' for use as the instance.
822
823 binding = None
824
825 if isinstance(wrapped, _FunctionWrapperBase):
826 binding = wrapped._self_binding
827
828 if not binding:
829 if inspect.isbuiltin(wrapped):
830 binding = 'builtin'
831
832 elif inspect.isfunction(wrapped):
833 binding = 'function'
834
835 elif inspect.isclass(wrapped):
836 binding = 'class'
837
838 elif isinstance(wrapped, classmethod):
839 binding = 'classmethod'
840
841 elif isinstance(wrapped, staticmethod):
842 binding = 'staticmethod'
843
844 elif hasattr(wrapped, '__self__'):
845 if inspect.isclass(wrapped.__self__):
846 binding = 'classmethod'
847 elif inspect.ismethod(wrapped):
848 binding = 'instancemethod'
849 else:
850 binding = 'callable'
851
852 else:
853 binding = 'callable'
854
855 super(FunctionWrapper, self).__init__(wrapped, None, wrapper,
856 enabled, binding)