Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/decorator/__init__.py: 56%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# ######################### LICENSE ############################ #
3# Copyright (c) 2005-2026, 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
40import functools
41from contextlib import _GeneratorContextManager
42from collections import namedtuple
43from inspect import Parameter, iscoroutinefunction, isgeneratorfunction
44from typing import Any, Dict, List, Optional
45try:
46 import annotationlib # in Python 3.14+
48 def inspect_sig(func):
49 return inspect.signature(
50 func, annotation_format=annotationlib.Format.FORWARDREF)
52except ImportError:
53 inspect_sig = inspect.signature
55__version__ = '5.3.1'
57DEF = re.compile(r'\s*def\s*([_\w][_\w\d]*)\s*\(')
58POS = inspect.Parameter.POSITIONAL_OR_KEYWORD
59EMPTY = inspect.Parameter.empty
60FullArgSpec = namedtuple('FullArgSpec', [
61 'args', 'varargs', 'varkw', 'defaults',
62 'kwonlyargs', 'kwonlydefaults', 'annotations'
63])
66def getfullargspec(func):
67 """
68 A pure re-implementation of inspect.getfullargspec(func)
69 built entirely on top of the modern inspect.signature API.
70 This is needed to work around a python 3.14 forward references bug.
71 """
72 sig = inspect_sig(func)
74 args = []
75 varargs = None
76 varkw = None
77 defaults_list = []
78 kwonlyargs = []
79 kwonlydefaults = {}
80 annotations = {}
82 # Process return annotation if it exists
83 if sig.return_annotation is not inspect.Signature.empty:
84 annotations['return'] = sig.return_annotation
86 for name, param in sig.parameters.items():
87 # Collect annotations for any parameter that defines one
88 if param.annotation is not Parameter.empty:
89 annotations[name] = param.annotation
91 # Segment parameters by their operational "kind"
92 if param.kind in (Parameter.POSITIONAL_ONLY,
93 Parameter.POSITIONAL_OR_KEYWORD):
94 args.append(name)
95 # Track defaults for standard positional arguments
96 if param.default is not Parameter.empty:
97 defaults_list.append(param.default)
98 else:
99 # Legacy behavior quirk: if a non-default argument follows a
100 # defaulted positional-only argument, the previous defaults
101 # are wiped
102 defaults_list.clear()
104 elif param.kind == Parameter.VAR_POSITIONAL:
105 varargs = name
107 elif param.kind == Parameter.KEYWORD_ONLY:
108 kwonlyargs.append(name)
109 if param.default is not Parameter.empty:
110 kwonlydefaults[name] = param.default
112 elif param.kind == Parameter.VAR_KEYWORD:
113 varkw = name
115 # Format output fields to match precise spec specifications
116 defaults = tuple(defaults_list) if defaults_list else None
117 kwonlydefaults = kwonlydefaults if kwonlydefaults else None
119 return FullArgSpec(args, varargs, varkw, defaults, kwonlyargs,
120 kwonlydefaults, annotations)
123# this is not used anymore in the core, but kept for backward compatibility
124class FunctionMaker:
125 """
126 An object with the ability to create functions with a given signature.
127 It has attributes name, doc, module, signature, defaults, dict and
128 methods update and make.
129 """
131 # Atomic get-and-increment provided by the GIL
132 _compile_count = itertools.count()
134 # make pylint happy
135 args: List[str] = []
136 varargs = varkw = defaults = None
137 kwonlyargs: List[str] = []
138 kwonlydefaults: Optional[Dict[str, Any]] = None
140 def __init__(self, func=None, name=None, signature=None,
141 defaults=None, doc=None, module=None, funcdict=None):
142 self.shortsignature = signature
143 if func:
144 # func can be a class or a callable, but not an instance method
145 self.name = func.__name__
146 if self.name == '<lambda>': # small hack for lambda functions
147 self.name = '_lambda_'
148 self.doc = func.__doc__
149 self.module = func.__module__
150 if inspect.isroutine(func) or isinstance(func, functools.partial):
151 argspec = getfullargspec(func)
152 self.annotations = getattr(func, '__annotations__', {})
153 for a in ('args', 'varargs', 'varkw', 'defaults', 'kwonlyargs',
154 'kwonlydefaults'):
155 setattr(self, a, getattr(argspec, a))
156 for i, arg in enumerate(self.args):
157 setattr(self, 'arg%d' % i, arg)
158 allargs = list(self.args)
159 allshortargs = list(self.args)
160 if self.varargs:
161 allargs.append('*' + self.varargs)
162 allshortargs.append('*' + self.varargs)
163 elif self.kwonlyargs:
164 allargs.append('*') # single star syntax
165 for a in self.kwonlyargs:
166 allargs.append('%s=None' % a)
167 allshortargs.append('{}={}'.format(a, a))
168 if self.varkw:
169 allargs.append('**' + self.varkw)
170 allshortargs.append('**' + self.varkw)
171 self.signature = ', '.join(allargs)
172 self.shortsignature = ', '.join(allshortargs)
173 self.dict = func.__dict__.copy()
174 # func=None happens when decorating a caller
175 if name:
176 self.name = name
177 if signature is not None:
178 self.signature = signature
179 if defaults:
180 self.defaults = defaults
181 if doc:
182 self.doc = doc
183 if module:
184 self.module = module
185 if funcdict:
186 self.dict = funcdict
187 # check existence required attributes
188 assert hasattr(self, 'name')
189 if not hasattr(self, 'signature'):
190 raise TypeError('You are decorating a non function: %s' % func)
192 def update(self, func, **kw):
193 """
194 Update the signature of func with the data in self
195 """
196 func.__name__ = self.name
197 func.__doc__ = getattr(self, 'doc', None)
198 func.__dict__ = getattr(self, 'dict', {})
199 func.__defaults__ = self.defaults
200 func.__kwdefaults__ = self.kwonlydefaults or None
201 func.__annotations__ = getattr(self, 'annotations', None)
202 try:
203 frame = sys._getframe(3)
204 except AttributeError: # for IronPython and similar implementations
205 callermodule = '?'
206 else:
207 callermodule = frame.f_globals.get('__name__', '?')
208 func.__module__ = getattr(self, 'module', callermodule)
209 func.__dict__.update(kw)
211 def make(self, src_templ, evaldict=None, addsource=False, **attrs):
212 """
213 Make a new function from a given template and update the signature
214 """
215 src = src_templ % vars(self) # expand name and signature
216 evaldict = evaldict or {}
217 mo = DEF.search(src)
218 if mo is None:
219 raise SyntaxError('not a valid function template\n%s' % src)
220 name = mo.group(1) # extract the function name
221 names = set([name] + [arg.strip(' *') for arg in
222 self.shortsignature.split(',')])
223 for n in names:
224 if n in ('_func_', '_call_'):
225 raise NameError('{} is overridden in\n{}'.format(n, src))
227 if not src.endswith('\n'): # add a newline for old Pythons
228 src += '\n'
230 # Ensure each generated function has a unique filename for profilers
231 # (such as cProfile) that depend on the tuple of (<filename>,
232 # <definition line>, <function name>) being unique.
233 filename = '<decorator-gen-%d>' % next(self._compile_count)
234 try:
235 code = compile(src, filename, 'single')
236 exec(code, evaldict)
237 except Exception:
238 print('Error in generated code:', file=sys.stderr)
239 print(src, file=sys.stderr)
240 raise
241 func = evaldict[name]
242 if addsource:
243 attrs['__source__'] = src
244 self.update(func, **attrs)
245 return func
247 @classmethod
248 def create(cls, obj, body, evaldict, defaults=None,
249 doc=None, module=None, addsource=True, **attrs):
250 """
251 Create a function from the strings name, signature and body.
252 evaldict is the evaluation dictionary. If addsource is true an
253 attribute __source__ is added to the result. The attributes attrs
254 are added, if any.
255 """
256 if isinstance(obj, str): # "name(signature)" or "name(signature) -> ret"
257 name, rest = obj.strip().split('(', 1)
258 # split the argument list from an optional return annotation;
259 # the argument list ends at the last right parens
260 signature, _, return_annotation = rest.rpartition(')')
261 func = None
262 else: # a function
263 name = None
264 signature = None
265 return_annotation = ''
266 func = obj
267 self = cls(func, name, signature, defaults, doc, module)
268 self.return_annotation = return_annotation # e.g. " -> int"
269 ibody = '\n'.join(' ' + line for line in body.splitlines())
270 caller = evaldict.get('_call_') # when called from `decorate`
271 if caller and iscoroutinefunction(caller):
272 body = ('async def %(name)s(%(signature)s)'
273 '%(return_annotation)s:\n' + ibody)
274 body = re.sub(r'\breturn\b', 'return await', body)
275 else:
276 body = ('def %(name)s(%(signature)s)'
277 '%(return_annotation)s:\n' + ibody)
278 return self.make(body, evaldict, addsource, **attrs)
281def fix(args, kwargs, sig):
282 """
283 Fix args and kwargs to be consistent with the signature
284 """
285 ba = sig.bind(*args, **kwargs)
286 ba.apply_defaults() # needed for test_dan_schult
287 return ba.args, ba.kwargs
290def decorate(func, caller, extras=(), kwsyntax=False):
291 """
292 Decorates a function/generator/coroutine using a caller.
293 If kwsyntax is True calling the decorated functions with keyword
294 syntax will pass the named arguments inside the ``kw`` dictionary,
295 even if such argument are positional, similarly to what functools.wraps
296 does. By default kwsyntax is False and the the arguments are untouched.
297 """
298 sig = inspect_sig(func)
299 if isinstance(func, functools.partial):
300 func = functools.update_wrapper(func, func.func)
301 if iscoroutinefunction(caller):
302 async def fun(*args, **kw):
303 if not kwsyntax:
304 args, kw = fix(args, kw, sig)
305 return await caller(func, *(extras + args), **kw)
306 elif isgeneratorfunction(caller):
307 def fun(*args, **kw):
308 if not kwsyntax:
309 args, kw = fix(args, kw, sig)
310 yield from caller(func, *(extras + args), **kw)
311 else:
312 def fun(*args, **kw):
313 if not kwsyntax:
314 args, kw = fix(args, kw, sig)
315 return caller(func, *(extras + args), **kw)
317 fun.__doc__ = func.__doc__
318 fun.__wrapped__ = func
319 fun.__signature__ = sig
320 fun.__qualname__ = func.__qualname__
321 # builtin functions like defaultdict.__setitem__ lack many attributes
322 try:
323 fun.__defaults__ = func.__defaults__
324 except AttributeError:
325 pass
326 try:
327 fun.__kwdefaults__ = func.__kwdefaults__
328 except AttributeError:
329 pass
330 try:
331 fun.__annotations__ = func.__annotations__
332 except (AttributeError, NameError):
333 pass
334 try:
335 fun.__module__ = func.__module__
336 except AttributeError:
337 pass
338 try:
339 fun.__name__ = func.__name__
340 except AttributeError: # happens with old versions of numpy.vectorize
341 func.__name__ == 'noname'
342 try:
343 fun.__dict__.update(func.__dict__)
344 except AttributeError:
345 pass
346 return fun
349def decoratorx(caller):
350 """
351 A version of "decorator" implemented via "exec" and not via the
352 Signature object. Use this if you are want to preserve the `.__code__`
353 object properties (https://github.com/micheles/decorator/issues/129).
354 """
355 def dec(func):
356 return FunctionMaker.create(
357 func,
358 "return _call_(_func_, %(shortsignature)s)",
359 dict(_call_=caller, _func_=func),
360 __wrapped__=func, __qualname__=func.__qualname__)
361 return dec
364def decorator(caller, _func=None, kwsyntax=False):
365 """
366 decorator(caller) converts a caller function into a decorator
367 """
368 if _func is not None: # return a decorated function
369 # this is obsolete behavior; you should use decorate instead
370 return decorate(_func, caller, (), kwsyntax)
371 # else return a decorator function
372 sig = inspect_sig(caller)
373 dec_params = [p for p in sig.parameters.values() if p.kind is POS]
375 def dec(func=None, *args, **kw):
376 na = len(args) + 1
377 extras = args + tuple(kw.get(p.name, p.default)
378 for p in dec_params[na:]
379 if p.default is not EMPTY)
380 if func is None:
381 return lambda func: decorate(func, caller, extras, kwsyntax)
382 else:
383 return decorate(func, caller, extras, kwsyntax)
384 dec.__signature__ = sig.replace(parameters=dec_params)
385 dec.__name__ = caller.__name__
386 dec.__doc__ = caller.__doc__
387 dec.__wrapped__ = caller
388 dec.__qualname__ = caller.__qualname__
389 dec.__kwdefaults__ = getattr(caller, '__kwdefaults__', None)
390 dec.__dict__.update(caller.__dict__)
391 return dec
394# ####################### contextmanager ####################### #
397class ContextManager(_GeneratorContextManager):
398 def __init__(self, g, *a, **k):
399 _GeneratorContextManager.__init__(self, g, a, k)
401 def __call__(self, func):
402 def caller(f, *a, **k):
403 with self.__class__(self.func, *self.args, **self.kwds):
404 return f(*a, **k)
405 return decorate(func, caller)
408_contextmanager = decorator(ContextManager)
411def contextmanager(func):
412 # Enable Pylint config: contextmanager-decorators=decorator.contextmanager
413 return _contextmanager(func)
416# ############################ dispatch_on ############################ #
418def append(a, vancestors):
419 """
420 Append ``a`` to the list of the virtual ancestors, unless it is already
421 included.
422 """
423 add = True
424 for j, va in enumerate(vancestors):
425 if issubclass(va, a):
426 add = False
427 break
428 if issubclass(a, va):
429 vancestors[j] = a
430 add = False
431 if add:
432 vancestors.append(a)
435# inspired from simplegeneric by P.J. Eby and functools.singledispatch
436def dispatch_on(*dispatch_args):
437 """
438 Factory of decorators turning a function into a generic function
439 dispatching on the given arguments.
440 """
441 assert dispatch_args, 'No dispatch args passed'
442 dispatch_str = '(%s,)' % ', '.join(dispatch_args)
444 def check(arguments, wrong=operator.ne, msg=''):
445 """Make sure one passes the expected number of arguments"""
446 if wrong(len(arguments), len(dispatch_args)):
447 raise TypeError('Expected %d arguments, got %d%s' %
448 (len(dispatch_args), len(arguments), msg))
450 def gen_func_dec(func):
451 """Decorator turning a function into a generic function"""
453 # first check the dispatch arguments
454 argset = set(getfullargspec(func).args)
455 if not set(dispatch_args) <= argset:
456 raise NameError('Unknown dispatch arguments %s' % dispatch_str)
458 typemap = {}
460 def vancestors(*types):
461 """
462 Get a list of sets of virtual ancestors for the given types
463 """
464 check(types)
465 ras = [[] for _ in range(len(dispatch_args))]
466 for types_ in typemap:
467 for t, type_, ra in zip(types, types_, ras):
468 if issubclass(t, type_) and type_ not in t.mro():
469 append(type_, ra)
470 return [set(ra) for ra in ras]
472 def ancestors(*types):
473 """
474 Get a list of virtual MROs, one for each type
475 """
476 check(types)
477 lists = []
478 for t, vas in zip(types, vancestors(*types)):
479 n_vas = len(vas)
480 if n_vas > 1:
481 raise RuntimeError(
482 'Ambiguous dispatch for {}: {}'.format(t, vas))
483 elif n_vas == 1:
484 va, = vas
485 mro = type('t', (t, va), {}).mro()[1:]
486 else:
487 mro = t.mro()
488 lists.append(mro[:-1]) # discard t and object
489 return lists
491 def register(*types):
492 """
493 Decorator to register an implementation for the given types
494 """
495 check(types)
497 def dec(f):
498 check(getfullargspec(f).args, operator.lt, ' in ' + f.__name__)
499 typemap[types] = f
500 return f
501 return dec
503 def dispatch_info(*types):
504 """
505 An utility to introspect the dispatch algorithm
506 """
507 check(types)
508 lst = []
509 for ancs in itertools.product(*ancestors(*types)):
510 lst.append(tuple(a.__name__ for a in ancs))
511 return lst
513 def _dispatch(dispatch_args, *args, **kw):
514 types = tuple(type(arg) for arg in dispatch_args)
515 try: # fast path
516 f = typemap[types]
517 except KeyError:
518 pass
519 else:
520 return f(*args, **kw)
521 combinations = itertools.product(*ancestors(*types))
522 next(combinations) # the first one has been already tried
523 for types_ in combinations:
524 f = typemap.get(types_)
525 if f is not None:
526 return f(*args, **kw)
528 # else call the default implementation
529 return func(*args, **kw)
531 return FunctionMaker.create(
532 func, 'return _f_(%s, %%(shortsignature)s)' % dispatch_str,
533 dict(_f_=_dispatch), register=register, default=func,
534 typemap=typemap, vancestors=vancestors, ancestors=ancestors,
535 dispatch_info=dispatch_info, __wrapped__=func)
537 gen_func_dec.__name__ = 'dispatch_on' + dispatch_str
538 return gen_func_dec