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)"
257 name, rest = obj.strip().split('(', 1)
258 signature = rest[:-1] # strip a right parens
259 func = None
260 else: # a function
261 name = None
262 signature = None
263 func = obj
264 self = cls(func, name, signature, defaults, doc, module)
265 ibody = '\n'.join(' ' + line for line in body.splitlines())
266 caller = evaldict.get('_call_') # when called from `decorate`
267 if caller and iscoroutinefunction(caller):
268 body = ('async def %(name)s(%(signature)s):\n' + ibody)
269 body = re.sub(r'\breturn\b', 'return await', body)
270 else:
271 body = 'def %(name)s(%(signature)s):\n' + ibody
272 return self.make(body, evaldict, addsource, **attrs)
275def fix(args, kwargs, sig):
276 """
277 Fix args and kwargs to be consistent with the signature
278 """
279 ba = sig.bind(*args, **kwargs)
280 ba.apply_defaults() # needed for test_dan_schult
281 return ba.args, ba.kwargs
284def decorate(func, caller, extras=(), kwsyntax=False):
285 """
286 Decorates a function/generator/coroutine using a caller.
287 If kwsyntax is True calling the decorated functions with keyword
288 syntax will pass the named arguments inside the ``kw`` dictionary,
289 even if such argument are positional, similarly to what functools.wraps
290 does. By default kwsyntax is False and the the arguments are untouched.
291 """
292 sig = inspect_sig(func)
293 if isinstance(func, functools.partial):
294 func = functools.update_wrapper(func, func.func)
295 if iscoroutinefunction(caller):
296 async def fun(*args, **kw):
297 if not kwsyntax:
298 args, kw = fix(args, kw, sig)
299 return await caller(func, *(extras + args), **kw)
300 elif isgeneratorfunction(caller):
301 def fun(*args, **kw):
302 if not kwsyntax:
303 args, kw = fix(args, kw, sig)
304 yield from caller(func, *(extras + args), **kw)
305 else:
306 def fun(*args, **kw):
307 if not kwsyntax:
308 args, kw = fix(args, kw, sig)
309 return caller(func, *(extras + args), **kw)
311 fun.__doc__ = func.__doc__
312 fun.__wrapped__ = func
313 fun.__signature__ = sig
314 fun.__qualname__ = func.__qualname__
315 # builtin functions like defaultdict.__setitem__ lack many attributes
316 try:
317 fun.__defaults__ = func.__defaults__
318 except AttributeError:
319 pass
320 try:
321 fun.__kwdefaults__ = func.__kwdefaults__
322 except AttributeError:
323 pass
324 try:
325 fun.__annotations__ = func.__annotations__
326 except (AttributeError, NameError):
327 pass
328 try:
329 fun.__module__ = func.__module__
330 except AttributeError:
331 pass
332 try:
333 fun.__name__ = func.__name__
334 except AttributeError: # happens with old versions of numpy.vectorize
335 func.__name__ == 'noname'
336 try:
337 fun.__dict__.update(func.__dict__)
338 except AttributeError:
339 pass
340 return fun
343def decoratorx(caller):
344 """
345 A version of "decorator" implemented via "exec" and not via the
346 Signature object. Use this if you are want to preserve the `.__code__`
347 object properties (https://github.com/micheles/decorator/issues/129).
348 """
349 def dec(func):
350 return FunctionMaker.create(
351 func,
352 "return _call_(_func_, %(shortsignature)s)",
353 dict(_call_=caller, _func_=func),
354 __wrapped__=func, __qualname__=func.__qualname__)
355 return dec
358def decorator(caller, _func=None, kwsyntax=False):
359 """
360 decorator(caller) converts a caller function into a decorator
361 """
362 if _func is not None: # return a decorated function
363 # this is obsolete behavior; you should use decorate instead
364 return decorate(_func, caller, (), kwsyntax)
365 # else return a decorator function
366 sig = inspect_sig(caller)
367 dec_params = [p for p in sig.parameters.values() if p.kind is POS]
369 def dec(func=None, *args, **kw):
370 na = len(args) + 1
371 extras = args + tuple(kw.get(p.name, p.default)
372 for p in dec_params[na:]
373 if p.default is not EMPTY)
374 if func is None:
375 return lambda func: decorate(func, caller, extras, kwsyntax)
376 else:
377 return decorate(func, caller, extras, kwsyntax)
378 dec.__signature__ = sig.replace(parameters=dec_params)
379 dec.__name__ = caller.__name__
380 dec.__doc__ = caller.__doc__
381 dec.__wrapped__ = caller
382 dec.__qualname__ = caller.__qualname__
383 dec.__kwdefaults__ = getattr(caller, '__kwdefaults__', None)
384 dec.__dict__.update(caller.__dict__)
385 return dec
388# ####################### contextmanager ####################### #
391class ContextManager(_GeneratorContextManager):
392 def __init__(self, g, *a, **k):
393 _GeneratorContextManager.__init__(self, g, a, k)
395 def __call__(self, func):
396 def caller(f, *a, **k):
397 with self.__class__(self.func, *self.args, **self.kwds):
398 return f(*a, **k)
399 return decorate(func, caller)
402_contextmanager = decorator(ContextManager)
405def contextmanager(func):
406 # Enable Pylint config: contextmanager-decorators=decorator.contextmanager
407 return _contextmanager(func)
410# ############################ dispatch_on ############################ #
412def append(a, vancestors):
413 """
414 Append ``a`` to the list of the virtual ancestors, unless it is already
415 included.
416 """
417 add = True
418 for j, va in enumerate(vancestors):
419 if issubclass(va, a):
420 add = False
421 break
422 if issubclass(a, va):
423 vancestors[j] = a
424 add = False
425 if add:
426 vancestors.append(a)
429# inspired from simplegeneric by P.J. Eby and functools.singledispatch
430def dispatch_on(*dispatch_args):
431 """
432 Factory of decorators turning a function into a generic function
433 dispatching on the given arguments.
434 """
435 assert dispatch_args, 'No dispatch args passed'
436 dispatch_str = '(%s,)' % ', '.join(dispatch_args)
438 def check(arguments, wrong=operator.ne, msg=''):
439 """Make sure one passes the expected number of arguments"""
440 if wrong(len(arguments), len(dispatch_args)):
441 raise TypeError('Expected %d arguments, got %d%s' %
442 (len(dispatch_args), len(arguments), msg))
444 def gen_func_dec(func):
445 """Decorator turning a function into a generic function"""
447 # first check the dispatch arguments
448 argset = set(getfullargspec(func).args)
449 if not set(dispatch_args) <= argset:
450 raise NameError('Unknown dispatch arguments %s' % dispatch_str)
452 typemap = {}
454 def vancestors(*types):
455 """
456 Get a list of sets of virtual ancestors for the given types
457 """
458 check(types)
459 ras = [[] for _ in range(len(dispatch_args))]
460 for types_ in typemap:
461 for t, type_, ra in zip(types, types_, ras):
462 if issubclass(t, type_) and type_ not in t.mro():
463 append(type_, ra)
464 return [set(ra) for ra in ras]
466 def ancestors(*types):
467 """
468 Get a list of virtual MROs, one for each type
469 """
470 check(types)
471 lists = []
472 for t, vas in zip(types, vancestors(*types)):
473 n_vas = len(vas)
474 if n_vas > 1:
475 raise RuntimeError(
476 'Ambiguous dispatch for {}: {}'.format(t, vas))
477 elif n_vas == 1:
478 va, = vas
479 mro = type('t', (t, va), {}).mro()[1:]
480 else:
481 mro = t.mro()
482 lists.append(mro[:-1]) # discard t and object
483 return lists
485 def register(*types):
486 """
487 Decorator to register an implementation for the given types
488 """
489 check(types)
491 def dec(f):
492 check(getfullargspec(f).args, operator.lt, ' in ' + f.__name__)
493 typemap[types] = f
494 return f
495 return dec
497 def dispatch_info(*types):
498 """
499 An utility to introspect the dispatch algorithm
500 """
501 check(types)
502 lst = []
503 for ancs in itertools.product(*ancestors(*types)):
504 lst.append(tuple(a.__name__ for a in ancs))
505 return lst
507 def _dispatch(dispatch_args, *args, **kw):
508 types = tuple(type(arg) for arg in dispatch_args)
509 try: # fast path
510 f = typemap[types]
511 except KeyError:
512 pass
513 else:
514 return f(*args, **kw)
515 combinations = itertools.product(*ancestors(*types))
516 next(combinations) # the first one has been already tried
517 for types_ in combinations:
518 f = typemap.get(types_)
519 if f is not None:
520 return f(*args, **kw)
522 # else call the default implementation
523 return func(*args, **kw)
525 return FunctionMaker.create(
526 func, 'return _f_(%s, %%(shortsignature)s)' % dispatch_str,
527 dict(_f_=_dispatch), register=register, default=func,
528 typemap=typemap, vancestors=vancestors, ancestors=ancestors,
529 dispatch_info=dispatch_info, __wrapped__=func)
531 gen_func_dec.__name__ = 'dispatch_on' + dispatch_str
532 return gen_func_dec