Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/decorator.py: 25%
271 statements
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-20 06:09 +0000
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-20 06:09 +0000
1# ######################### LICENSE ############################ #
3# Copyright (c) 2005-2021, Michele Simionato
4# All rights reserved.
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions are
8# met:
10# Redistributions of source code must retain the above copyright
11# notice, this list of conditions and the following disclaimer.
12# Redistributions in bytecode form must reproduce the above copyright
13# notice, this list of conditions and the following disclaimer in
14# the documentation and/or other materials provided with the
15# distribution.
17# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21# HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
22# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
23# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
24# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
26# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
27# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
28# DAMAGE.
30"""
31Decorator module, see
32https://github.com/micheles/decorator/blob/master/docs/documentation.md
33for the documentation.
34"""
35import re
36import sys
37import inspect
38import operator
39import itertools
40from contextlib import _GeneratorContextManager
41from inspect import getfullargspec, iscoroutinefunction, isgeneratorfunction
43__version__ = '5.1.1'
45DEF = re.compile(r'\s*def\s*([_\w][_\w\d]*)\s*\(')
46POS = inspect.Parameter.POSITIONAL_OR_KEYWORD
47EMPTY = inspect.Parameter.empty
50# this is not used anymore in the core, but kept for backward compatibility
51class FunctionMaker(object):
52 """
53 An object with the ability to create functions with a given signature.
54 It has attributes name, doc, module, signature, defaults, dict and
55 methods update and make.
56 """
58 # Atomic get-and-increment provided by the GIL
59 _compile_count = itertools.count()
61 # make pylint happy
62 args = varargs = varkw = defaults = kwonlyargs = kwonlydefaults = ()
64 def __init__(self, func=None, name=None, signature=None,
65 defaults=None, doc=None, module=None, funcdict=None):
66 self.shortsignature = signature
67 if func:
68 # func can be a class or a callable, but not an instance method
69 self.name = func.__name__
70 if self.name == '<lambda>': # small hack for lambda functions
71 self.name = '_lambda_'
72 self.doc = func.__doc__
73 self.module = func.__module__
74 if inspect.isroutine(func):
75 argspec = getfullargspec(func)
76 self.annotations = getattr(func, '__annotations__', {})
77 for a in ('args', 'varargs', 'varkw', 'defaults', 'kwonlyargs',
78 'kwonlydefaults'):
79 setattr(self, a, getattr(argspec, a))
80 for i, arg in enumerate(self.args):
81 setattr(self, 'arg%d' % i, arg)
82 allargs = list(self.args)
83 allshortargs = list(self.args)
84 if self.varargs:
85 allargs.append('*' + self.varargs)
86 allshortargs.append('*' + self.varargs)
87 elif self.kwonlyargs:
88 allargs.append('*') # single star syntax
89 for a in self.kwonlyargs:
90 allargs.append('%s=None' % a)
91 allshortargs.append('%s=%s' % (a, a))
92 if self.varkw:
93 allargs.append('**' + self.varkw)
94 allshortargs.append('**' + self.varkw)
95 self.signature = ', '.join(allargs)
96 self.shortsignature = ', '.join(allshortargs)
97 self.dict = func.__dict__.copy()
98 # func=None happens when decorating a caller
99 if name:
100 self.name = name
101 if signature is not None:
102 self.signature = signature
103 if defaults:
104 self.defaults = defaults
105 if doc:
106 self.doc = doc
107 if module:
108 self.module = module
109 if funcdict:
110 self.dict = funcdict
111 # check existence required attributes
112 assert hasattr(self, 'name')
113 if not hasattr(self, 'signature'):
114 raise TypeError('You are decorating a non function: %s' % func)
116 def update(self, func, **kw):
117 """
118 Update the signature of func with the data in self
119 """
120 func.__name__ = self.name
121 func.__doc__ = getattr(self, 'doc', None)
122 func.__dict__ = getattr(self, 'dict', {})
123 func.__defaults__ = self.defaults
124 func.__kwdefaults__ = self.kwonlydefaults or None
125 func.__annotations__ = getattr(self, 'annotations', None)
126 try:
127 frame = sys._getframe(3)
128 except AttributeError: # for IronPython and similar implementations
129 callermodule = '?'
130 else:
131 callermodule = frame.f_globals.get('__name__', '?')
132 func.__module__ = getattr(self, 'module', callermodule)
133 func.__dict__.update(kw)
135 def make(self, src_templ, evaldict=None, addsource=False, **attrs):
136 """
137 Make a new function from a given template and update the signature
138 """
139 src = src_templ % vars(self) # expand name and signature
140 evaldict = evaldict or {}
141 mo = DEF.search(src)
142 if mo is None:
143 raise SyntaxError('not a valid function template\n%s' % src)
144 name = mo.group(1) # extract the function name
145 names = set([name] + [arg.strip(' *') for arg in
146 self.shortsignature.split(',')])
147 for n in names:
148 if n in ('_func_', '_call_'):
149 raise NameError('%s is overridden in\n%s' % (n, src))
151 if not src.endswith('\n'): # add a newline for old Pythons
152 src += '\n'
154 # Ensure each generated function has a unique filename for profilers
155 # (such as cProfile) that depend on the tuple of (<filename>,
156 # <definition line>, <function name>) being unique.
157 filename = '<decorator-gen-%d>' % next(self._compile_count)
158 try:
159 code = compile(src, filename, 'single')
160 exec(code, evaldict)
161 except Exception:
162 print('Error in generated code:', file=sys.stderr)
163 print(src, file=sys.stderr)
164 raise
165 func = evaldict[name]
166 if addsource:
167 attrs['__source__'] = src
168 self.update(func, **attrs)
169 return func
171 @classmethod
172 def create(cls, obj, body, evaldict, defaults=None,
173 doc=None, module=None, addsource=True, **attrs):
174 """
175 Create a function from the strings name, signature and body.
176 evaldict is the evaluation dictionary. If addsource is true an
177 attribute __source__ is added to the result. The attributes attrs
178 are added, if any.
179 """
180 if isinstance(obj, str): # "name(signature)"
181 name, rest = obj.strip().split('(', 1)
182 signature = rest[:-1] # strip a right parens
183 func = None
184 else: # a function
185 name = None
186 signature = None
187 func = obj
188 self = cls(func, name, signature, defaults, doc, module)
189 ibody = '\n'.join(' ' + line for line in body.splitlines())
190 caller = evaldict.get('_call_') # when called from `decorate`
191 if caller and iscoroutinefunction(caller):
192 body = ('async def %(name)s(%(signature)s):\n' + ibody).replace(
193 'return', 'return await')
194 else:
195 body = 'def %(name)s(%(signature)s):\n' + ibody
196 return self.make(body, evaldict, addsource, **attrs)
199def fix(args, kwargs, sig):
200 """
201 Fix args and kwargs to be consistent with the signature
202 """
203 ba = sig.bind(*args, **kwargs)
204 ba.apply_defaults() # needed for test_dan_schult
205 return ba.args, ba.kwargs
208def decorate(func, caller, extras=(), kwsyntax=False):
209 """
210 Decorates a function/generator/coroutine using a caller.
211 If kwsyntax is True calling the decorated functions with keyword
212 syntax will pass the named arguments inside the ``kw`` dictionary,
213 even if such argument are positional, similarly to what functools.wraps
214 does. By default kwsyntax is False and the the arguments are untouched.
215 """
216 sig = inspect.signature(func)
217 if iscoroutinefunction(caller):
218 async def fun(*args, **kw):
219 if not kwsyntax:
220 args, kw = fix(args, kw, sig)
221 return await caller(func, *(extras + args), **kw)
222 elif isgeneratorfunction(caller):
223 def fun(*args, **kw):
224 if not kwsyntax:
225 args, kw = fix(args, kw, sig)
226 for res in caller(func, *(extras + args), **kw):
227 yield res
228 else:
229 def fun(*args, **kw):
230 if not kwsyntax:
231 args, kw = fix(args, kw, sig)
232 return caller(func, *(extras + args), **kw)
233 fun.__name__ = func.__name__
234 fun.__doc__ = func.__doc__
235 fun.__wrapped__ = func
236 fun.__signature__ = sig
237 fun.__qualname__ = func.__qualname__
238 # builtin functions like defaultdict.__setitem__ lack many attributes
239 try:
240 fun.__defaults__ = func.__defaults__
241 except AttributeError:
242 pass
243 try:
244 fun.__kwdefaults__ = func.__kwdefaults__
245 except AttributeError:
246 pass
247 try:
248 fun.__annotations__ = func.__annotations__
249 except AttributeError:
250 pass
251 try:
252 fun.__module__ = func.__module__
253 except AttributeError:
254 pass
255 try:
256 fun.__dict__.update(func.__dict__)
257 except AttributeError:
258 pass
259 return fun
262def decoratorx(caller):
263 """
264 A version of "decorator" implemented via "exec" and not via the
265 Signature object. Use this if you are want to preserve the `.__code__`
266 object properties (https://github.com/micheles/decorator/issues/129).
267 """
268 def dec(func):
269 return FunctionMaker.create(
270 func,
271 "return _call_(_func_, %(shortsignature)s)",
272 dict(_call_=caller, _func_=func),
273 __wrapped__=func, __qualname__=func.__qualname__)
274 return dec
277def decorator(caller, _func=None, kwsyntax=False):
278 """
279 decorator(caller) converts a caller function into a decorator
280 """
281 if _func is not None: # return a decorated function
282 # this is obsolete behavior; you should use decorate instead
283 return decorate(_func, caller, (), kwsyntax)
284 # else return a decorator function
285 sig = inspect.signature(caller)
286 dec_params = [p for p in sig.parameters.values() if p.kind is POS]
288 def dec(func=None, *args, **kw):
289 na = len(args) + 1
290 extras = args + tuple(kw.get(p.name, p.default)
291 for p in dec_params[na:]
292 if p.default is not EMPTY)
293 if func is None:
294 return lambda func: decorate(func, caller, extras, kwsyntax)
295 else:
296 return decorate(func, caller, extras, kwsyntax)
297 dec.__signature__ = sig.replace(parameters=dec_params)
298 dec.__name__ = caller.__name__
299 dec.__doc__ = caller.__doc__
300 dec.__wrapped__ = caller
301 dec.__qualname__ = caller.__qualname__
302 dec.__kwdefaults__ = getattr(caller, '__kwdefaults__', None)
303 dec.__dict__.update(caller.__dict__)
304 return dec
307# ####################### contextmanager ####################### #
310class ContextManager(_GeneratorContextManager):
311 def __init__(self, g, *a, **k):
312 _GeneratorContextManager.__init__(self, g, a, k)
314 def __call__(self, func):
315 def caller(f, *a, **k):
316 with self.__class__(self.func, *self.args, **self.kwds):
317 return f(*a, **k)
318 return decorate(func, caller)
321_contextmanager = decorator(ContextManager)
324def contextmanager(func):
325 # Enable Pylint config: contextmanager-decorators=decorator.contextmanager
326 return _contextmanager(func)
329# ############################ dispatch_on ############################ #
331def append(a, vancestors):
332 """
333 Append ``a`` to the list of the virtual ancestors, unless it is already
334 included.
335 """
336 add = True
337 for j, va in enumerate(vancestors):
338 if issubclass(va, a):
339 add = False
340 break
341 if issubclass(a, va):
342 vancestors[j] = a
343 add = False
344 if add:
345 vancestors.append(a)
348# inspired from simplegeneric by P.J. Eby and functools.singledispatch
349def dispatch_on(*dispatch_args):
350 """
351 Factory of decorators turning a function into a generic function
352 dispatching on the given arguments.
353 """
354 assert dispatch_args, 'No dispatch args passed'
355 dispatch_str = '(%s,)' % ', '.join(dispatch_args)
357 def check(arguments, wrong=operator.ne, msg=''):
358 """Make sure one passes the expected number of arguments"""
359 if wrong(len(arguments), len(dispatch_args)):
360 raise TypeError('Expected %d arguments, got %d%s' %
361 (len(dispatch_args), len(arguments), msg))
363 def gen_func_dec(func):
364 """Decorator turning a function into a generic function"""
366 # first check the dispatch arguments
367 argset = set(getfullargspec(func).args)
368 if not set(dispatch_args) <= argset:
369 raise NameError('Unknown dispatch arguments %s' % dispatch_str)
371 typemap = {}
373 def vancestors(*types):
374 """
375 Get a list of sets of virtual ancestors for the given types
376 """
377 check(types)
378 ras = [[] for _ in range(len(dispatch_args))]
379 for types_ in typemap:
380 for t, type_, ra in zip(types, types_, ras):
381 if issubclass(t, type_) and type_ not in t.mro():
382 append(type_, ra)
383 return [set(ra) for ra in ras]
385 def ancestors(*types):
386 """
387 Get a list of virtual MROs, one for each type
388 """
389 check(types)
390 lists = []
391 for t, vas in zip(types, vancestors(*types)):
392 n_vas = len(vas)
393 if n_vas > 1:
394 raise RuntimeError(
395 'Ambiguous dispatch for %s: %s' % (t, vas))
396 elif n_vas == 1:
397 va, = vas
398 mro = type('t', (t, va), {}).mro()[1:]
399 else:
400 mro = t.mro()
401 lists.append(mro[:-1]) # discard t and object
402 return lists
404 def register(*types):
405 """
406 Decorator to register an implementation for the given types
407 """
408 check(types)
410 def dec(f):
411 check(getfullargspec(f).args, operator.lt, ' in ' + f.__name__)
412 typemap[types] = f
413 return f
414 return dec
416 def dispatch_info(*types):
417 """
418 An utility to introspect the dispatch algorithm
419 """
420 check(types)
421 lst = []
422 for anc in itertools.product(*ancestors(*types)):
423 lst.append(tuple(a.__name__ for a in anc))
424 return lst
426 def _dispatch(dispatch_args, *args, **kw):
427 types = tuple(type(arg) for arg in dispatch_args)
428 try: # fast path
429 f = typemap[types]
430 except KeyError:
431 pass
432 else:
433 return f(*args, **kw)
434 combinations = itertools.product(*ancestors(*types))
435 next(combinations) # the first one has been already tried
436 for types_ in combinations:
437 f = typemap.get(types_)
438 if f is not None:
439 return f(*args, **kw)
441 # else call the default implementation
442 return func(*args, **kw)
444 return FunctionMaker.create(
445 func, 'return _f_(%s, %%(shortsignature)s)' % dispatch_str,
446 dict(_f_=_dispatch), register=register, default=func,
447 typemap=typemap, vancestors=vancestors, ancestors=ancestors,
448 dispatch_info=dispatch_info, __wrapped__=func)
450 gen_func_dec.__name__ = 'dispatch_on' + dispatch_str
451 return gen_func_dec