Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/decorator/__init__.py: 29%

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

288 statements  

1# ######################### LICENSE ############################ # 

2 

3# Copyright (c) 2005-2026, Michele Simionato 

4# All rights reserved. 

5 

6# Redistribution and use in source and binary forms, with or without 

7# modification, are permitted provided that the following conditions are 

8# met: 

9 

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. 

16 

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. 

29 

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 inspect import getfullargspec, iscoroutinefunction, isgeneratorfunction 

43from typing import Any, Dict, List, Optional 

44try: 

45 import annotationlib # in Python 3.14+ 

46 

47 def inspect_sig(func): 

48 return inspect.signature( 

49 func, annotation_format=annotationlib.Format.FORWARDREF) 

50 

51except ImportError: 

52 inspect_sig = inspect.signature 

53 

54__version__ = '5.3.1' 

55 

56DEF = re.compile(r'\s*def\s*([_\w][_\w\d]*)\s*\(') 

57POS = inspect.Parameter.POSITIONAL_OR_KEYWORD 

58EMPTY = inspect.Parameter.empty 

59 

60 

61# this is not used anymore in the core, but kept for backward compatibility 

62class FunctionMaker: 

63 """ 

64 An object with the ability to create functions with a given signature. 

65 It has attributes name, doc, module, signature, defaults, dict and 

66 methods update and make. 

67 """ 

68 

69 # Atomic get-and-increment provided by the GIL 

70 _compile_count = itertools.count() 

71 

72 # make pylint happy 

73 args: List[str] = [] 

74 varargs = varkw = defaults = None 

75 kwonlyargs: List[str] = [] 

76 kwonlydefaults: Optional[Dict[str, Any]] = None 

77 

78 def __init__(self, func=None, name=None, signature=None, 

79 defaults=None, doc=None, module=None, funcdict=None): 

80 self.shortsignature = signature 

81 if func: 

82 # func can be a class or a callable, but not an instance method 

83 self.name = func.__name__ 

84 if self.name == '<lambda>': # small hack for lambda functions 

85 self.name = '_lambda_' 

86 self.doc = func.__doc__ 

87 self.module = func.__module__ 

88 if inspect.isroutine(func) or isinstance(func, functools.partial): 

89 argspec = getfullargspec(func) 

90 self.annotations = getattr(func, '__annotations__', {}) 

91 for a in ('args', 'varargs', 'varkw', 'defaults', 'kwonlyargs', 

92 'kwonlydefaults'): 

93 setattr(self, a, getattr(argspec, a)) 

94 for i, arg in enumerate(self.args): 

95 setattr(self, 'arg%d' % i, arg) 

96 allargs = list(self.args) 

97 allshortargs = list(self.args) 

98 if self.varargs: 

99 allargs.append('*' + self.varargs) 

100 allshortargs.append('*' + self.varargs) 

101 elif self.kwonlyargs: 

102 allargs.append('*') # single star syntax 

103 for a in self.kwonlyargs: 

104 allargs.append('%s=None' % a) 

105 allshortargs.append('{}={}'.format(a, a)) 

106 if self.varkw: 

107 allargs.append('**' + self.varkw) 

108 allshortargs.append('**' + self.varkw) 

109 self.signature = ', '.join(allargs) 

110 self.shortsignature = ', '.join(allshortargs) 

111 self.dict = func.__dict__.copy() 

112 # func=None happens when decorating a caller 

113 if name: 

114 self.name = name 

115 if signature is not None: 

116 self.signature = signature 

117 if defaults: 

118 self.defaults = defaults 

119 if doc: 

120 self.doc = doc 

121 if module: 

122 self.module = module 

123 if funcdict: 

124 self.dict = funcdict 

125 # check existence required attributes 

126 assert hasattr(self, 'name') 

127 if not hasattr(self, 'signature'): 

128 raise TypeError('You are decorating a non function: %s' % func) 

129 

130 def update(self, func, **kw): 

131 """ 

132 Update the signature of func with the data in self 

133 """ 

134 func.__name__ = self.name 

135 func.__doc__ = getattr(self, 'doc', None) 

136 func.__dict__ = getattr(self, 'dict', {}) 

137 func.__defaults__ = self.defaults 

138 func.__kwdefaults__ = self.kwonlydefaults or None 

139 func.__annotations__ = getattr(self, 'annotations', None) 

140 try: 

141 frame = sys._getframe(3) 

142 except AttributeError: # for IronPython and similar implementations 

143 callermodule = '?' 

144 else: 

145 callermodule = frame.f_globals.get('__name__', '?') 

146 func.__module__ = getattr(self, 'module', callermodule) 

147 func.__dict__.update(kw) 

148 

149 def make(self, src_templ, evaldict=None, addsource=False, **attrs): 

150 """ 

151 Make a new function from a given template and update the signature 

152 """ 

153 src = src_templ % vars(self) # expand name and signature 

154 evaldict = evaldict or {} 

155 mo = DEF.search(src) 

156 if mo is None: 

157 raise SyntaxError('not a valid function template\n%s' % src) 

158 name = mo.group(1) # extract the function name 

159 names = set([name] + [arg.strip(' *') for arg in 

160 self.shortsignature.split(',')]) 

161 for n in names: 

162 if n in ('_func_', '_call_'): 

163 raise NameError('{} is overridden in\n{}'.format(n, src)) 

164 

165 if not src.endswith('\n'): # add a newline for old Pythons 

166 src += '\n' 

167 

168 # Ensure each generated function has a unique filename for profilers 

169 # (such as cProfile) that depend on the tuple of (<filename>, 

170 # <definition line>, <function name>) being unique. 

171 filename = '<decorator-gen-%d>' % next(self._compile_count) 

172 try: 

173 code = compile(src, filename, 'single') 

174 exec(code, evaldict) 

175 except Exception: 

176 print('Error in generated code:', file=sys.stderr) 

177 print(src, file=sys.stderr) 

178 raise 

179 func = evaldict[name] 

180 if addsource: 

181 attrs['__source__'] = src 

182 self.update(func, **attrs) 

183 return func 

184 

185 @classmethod 

186 def create(cls, obj, body, evaldict, defaults=None, 

187 doc=None, module=None, addsource=True, **attrs): 

188 """ 

189 Create a function from the strings name, signature and body. 

190 evaldict is the evaluation dictionary. If addsource is true an 

191 attribute __source__ is added to the result. The attributes attrs 

192 are added, if any. 

193 """ 

194 if isinstance(obj, str): # "name(signature)" 

195 name, rest = obj.strip().split('(', 1) 

196 signature = rest[:-1] # strip a right parens 

197 func = None 

198 else: # a function 

199 name = None 

200 signature = None 

201 func = obj 

202 self = cls(func, name, signature, defaults, doc, module) 

203 ibody = '\n'.join(' ' + line for line in body.splitlines()) 

204 caller = evaldict.get('_call_') # when called from `decorate` 

205 if caller and iscoroutinefunction(caller): 

206 body = ('async def %(name)s(%(signature)s):\n' + ibody) 

207 body = re.sub(r'\breturn\b', 'return await', body) 

208 else: 

209 body = 'def %(name)s(%(signature)s):\n' + ibody 

210 return self.make(body, evaldict, addsource, **attrs) 

211 

212 

213def fix(args, kwargs, sig): 

214 """ 

215 Fix args and kwargs to be consistent with the signature 

216 """ 

217 ba = sig.bind(*args, **kwargs) 

218 ba.apply_defaults() # needed for test_dan_schult 

219 return ba.args, ba.kwargs 

220 

221 

222def decorate(func, caller, extras=(), kwsyntax=False): 

223 """ 

224 Decorates a function/generator/coroutine using a caller. 

225 If kwsyntax is True calling the decorated functions with keyword 

226 syntax will pass the named arguments inside the ``kw`` dictionary, 

227 even if such argument are positional, similarly to what functools.wraps 

228 does. By default kwsyntax is False and the the arguments are untouched. 

229 """ 

230 sig = inspect_sig(func) 

231 if isinstance(func, functools.partial): 

232 func = functools.update_wrapper(func, func.func) 

233 if iscoroutinefunction(caller): 

234 async def fun(*args, **kw): 

235 if not kwsyntax: 

236 args, kw = fix(args, kw, sig) 

237 return await caller(func, *(extras + args), **kw) 

238 elif isgeneratorfunction(caller): 

239 def fun(*args, **kw): 

240 if not kwsyntax: 

241 args, kw = fix(args, kw, sig) 

242 yield from caller(func, *(extras + args), **kw) 

243 else: 

244 def fun(*args, **kw): 

245 if not kwsyntax: 

246 args, kw = fix(args, kw, sig) 

247 return caller(func, *(extras + args), **kw) 

248 

249 fun.__doc__ = func.__doc__ 

250 fun.__wrapped__ = func 

251 fun.__signature__ = sig 

252 fun.__qualname__ = func.__qualname__ 

253 # builtin functions like defaultdict.__setitem__ lack many attributes 

254 try: 

255 fun.__defaults__ = func.__defaults__ 

256 except AttributeError: 

257 pass 

258 try: 

259 fun.__kwdefaults__ = func.__kwdefaults__ 

260 except AttributeError: 

261 pass 

262 try: 

263 fun.__annotations__ = func.__annotations__ 

264 except AttributeError: 

265 pass 

266 try: 

267 fun.__module__ = func.__module__ 

268 except AttributeError: 

269 pass 

270 try: 

271 fun.__name__ = func.__name__ 

272 except AttributeError: # happens with old versions of numpy.vectorize 

273 func.__name__ == 'noname' 

274 try: 

275 fun.__dict__.update(func.__dict__) 

276 except AttributeError: 

277 pass 

278 return fun 

279 

280 

281def decoratorx(caller): 

282 """ 

283 A version of "decorator" implemented via "exec" and not via the 

284 Signature object. Use this if you are want to preserve the `.__code__` 

285 object properties (https://github.com/micheles/decorator/issues/129). 

286 """ 

287 def dec(func): 

288 return FunctionMaker.create( 

289 func, 

290 "return _call_(_func_, %(shortsignature)s)", 

291 dict(_call_=caller, _func_=func), 

292 __wrapped__=func, __qualname__=func.__qualname__) 

293 return dec 

294 

295 

296def decorator(caller, _func=None, kwsyntax=False): 

297 """ 

298 decorator(caller) converts a caller function into a decorator 

299 """ 

300 if _func is not None: # return a decorated function 

301 # this is obsolete behavior; you should use decorate instead 

302 return decorate(_func, caller, (), kwsyntax) 

303 # else return a decorator function 

304 sig = inspect_sig(caller) 

305 dec_params = [p for p in sig.parameters.values() if p.kind is POS] 

306 

307 def dec(func=None, *args, **kw): 

308 na = len(args) + 1 

309 extras = args + tuple(kw.get(p.name, p.default) 

310 for p in dec_params[na:] 

311 if p.default is not EMPTY) 

312 if func is None: 

313 return lambda func: decorate(func, caller, extras, kwsyntax) 

314 else: 

315 return decorate(func, caller, extras, kwsyntax) 

316 dec.__signature__ = sig.replace(parameters=dec_params) 

317 dec.__name__ = caller.__name__ 

318 dec.__doc__ = caller.__doc__ 

319 dec.__wrapped__ = caller 

320 dec.__qualname__ = caller.__qualname__ 

321 dec.__kwdefaults__ = getattr(caller, '__kwdefaults__', None) 

322 dec.__dict__.update(caller.__dict__) 

323 return dec 

324 

325 

326# ####################### contextmanager ####################### # 

327 

328 

329class ContextManager(_GeneratorContextManager): 

330 def __init__(self, g, *a, **k): 

331 _GeneratorContextManager.__init__(self, g, a, k) 

332 

333 def __call__(self, func): 

334 def caller(f, *a, **k): 

335 with self.__class__(self.func, *self.args, **self.kwds): 

336 return f(*a, **k) 

337 return decorate(func, caller) 

338 

339 

340_contextmanager = decorator(ContextManager) 

341 

342 

343def contextmanager(func): 

344 # Enable Pylint config: contextmanager-decorators=decorator.contextmanager 

345 return _contextmanager(func) 

346 

347 

348# ############################ dispatch_on ############################ # 

349 

350def append(a, vancestors): 

351 """ 

352 Append ``a`` to the list of the virtual ancestors, unless it is already 

353 included. 

354 """ 

355 add = True 

356 for j, va in enumerate(vancestors): 

357 if issubclass(va, a): 

358 add = False 

359 break 

360 if issubclass(a, va): 

361 vancestors[j] = a 

362 add = False 

363 if add: 

364 vancestors.append(a) 

365 

366 

367# inspired from simplegeneric by P.J. Eby and functools.singledispatch 

368def dispatch_on(*dispatch_args): 

369 """ 

370 Factory of decorators turning a function into a generic function 

371 dispatching on the given arguments. 

372 """ 

373 assert dispatch_args, 'No dispatch args passed' 

374 dispatch_str = '(%s,)' % ', '.join(dispatch_args) 

375 

376 def check(arguments, wrong=operator.ne, msg=''): 

377 """Make sure one passes the expected number of arguments""" 

378 if wrong(len(arguments), len(dispatch_args)): 

379 raise TypeError('Expected %d arguments, got %d%s' % 

380 (len(dispatch_args), len(arguments), msg)) 

381 

382 def gen_func_dec(func): 

383 """Decorator turning a function into a generic function""" 

384 

385 # first check the dispatch arguments 

386 argset = set(getfullargspec(func).args) 

387 if not set(dispatch_args) <= argset: 

388 raise NameError('Unknown dispatch arguments %s' % dispatch_str) 

389 

390 typemap = {} 

391 

392 def vancestors(*types): 

393 """ 

394 Get a list of sets of virtual ancestors for the given types 

395 """ 

396 check(types) 

397 ras = [[] for _ in range(len(dispatch_args))] 

398 for types_ in typemap: 

399 for t, type_, ra in zip(types, types_, ras): 

400 if issubclass(t, type_) and type_ not in t.mro(): 

401 append(type_, ra) 

402 return [set(ra) for ra in ras] 

403 

404 def ancestors(*types): 

405 """ 

406 Get a list of virtual MROs, one for each type 

407 """ 

408 check(types) 

409 lists = [] 

410 for t, vas in zip(types, vancestors(*types)): 

411 n_vas = len(vas) 

412 if n_vas > 1: 

413 raise RuntimeError( 

414 'Ambiguous dispatch for {}: {}'.format(t, vas)) 

415 elif n_vas == 1: 

416 va, = vas 

417 mro = type('t', (t, va), {}).mro()[1:] 

418 else: 

419 mro = t.mro() 

420 lists.append(mro[:-1]) # discard t and object 

421 return lists 

422 

423 def register(*types): 

424 """ 

425 Decorator to register an implementation for the given types 

426 """ 

427 check(types) 

428 

429 def dec(f): 

430 check(getfullargspec(f).args, operator.lt, ' in ' + f.__name__) 

431 typemap[types] = f 

432 return f 

433 return dec 

434 

435 def dispatch_info(*types): 

436 """ 

437 An utility to introspect the dispatch algorithm 

438 """ 

439 check(types) 

440 lst = [] 

441 for ancs in itertools.product(*ancestors(*types)): 

442 lst.append(tuple(a.__name__ for a in ancs)) 

443 return lst 

444 

445 def _dispatch(dispatch_args, *args, **kw): 

446 types = tuple(type(arg) for arg in dispatch_args) 

447 try: # fast path 

448 f = typemap[types] 

449 except KeyError: 

450 pass 

451 else: 

452 return f(*args, **kw) 

453 combinations = itertools.product(*ancestors(*types)) 

454 next(combinations) # the first one has been already tried 

455 for types_ in combinations: 

456 f = typemap.get(types_) 

457 if f is not None: 

458 return f(*args, **kw) 

459 

460 # else call the default implementation 

461 return func(*args, **kw) 

462 

463 return FunctionMaker.create( 

464 func, 'return _f_(%s, %%(shortsignature)s)' % dispatch_str, 

465 dict(_f_=_dispatch), register=register, default=func, 

466 typemap=typemap, vancestors=vancestors, ancestors=ancestors, 

467 dispatch_info=dispatch_info, __wrapped__=func) 

468 

469 gen_func_dec.__name__ = 'dispatch_on' + dispatch_str 

470 return gen_func_dec