Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

2 

3# Copyright (c) 2005-2021, 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 

40from contextlib import _GeneratorContextManager 

41from inspect import getfullargspec, iscoroutinefunction, isgeneratorfunction 

42 

43__version__ = '5.0.7' 

44 

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

46POS = inspect.Parameter.POSITIONAL_OR_KEYWORD 

47EMPTY = inspect.Parameter.empty 

48 

49 

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 """ 

57 

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

59 _compile_count = itertools.count() 

60 

61 # make pylint happy 

62 args = varargs = varkw = defaults = kwonlyargs = kwonlydefaults = () 

63 

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.isfunction(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) 

115 

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) 

134 

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)) 

150 

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

152 src += '\n' 

153 

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 

170 

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) 

197 

198 

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 

206 

207 

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.__defaults__ = func.__defaults__ 

236 fun.__kwdefaults__ = func.__kwdefaults__ 

237 fun.__annotations__ = func.__annotations__ 

238 fun.__module__ = func.__module__ 

239 fun.__signature__ = sig 

240 fun.__wrapped__ = func 

241 fun.__qualname__ = func.__qualname__ 

242 fun.__dict__.update(func.__dict__) 

243 return fun 

244 

245 

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

247 """ 

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

249 """ 

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

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

252 return decorate(_func, caller) 

253 # else return a decorator function 

254 sig = inspect.signature(caller) 

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

256 

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

258 na = len(args) + 1 

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

260 for p in dec_params[na:] 

261 if p.default is not EMPTY) 

262 if func is None: 

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

264 else: 

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

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

267 dec.__name__ = caller.__name__ 

268 dec.__doc__ = caller.__doc__ 

269 dec.__wrapped__ = caller 

270 dec.__qualname__ = caller.__qualname__ 

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

272 dec.__dict__.update(caller.__dict__) 

273 return dec 

274 

275 

276# ####################### contextmanager ####################### # 

277 

278 

279class ContextManager(_GeneratorContextManager): 

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

281 return _GeneratorContextManager.__init__(self, g, a, k) 

282 

283 def __call__(self, func): 

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

285 with self: 

286 return f(*a, **k) 

287 return decorate(func, caller) 

288 

289 

290_contextmanager = decorator(ContextManager) 

291 

292 

293def contextmanager(func): 

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

295 return _contextmanager(func) 

296 

297 

298# ############################ dispatch_on ############################ # 

299 

300def append(a, vancestors): 

301 """ 

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

303 included. 

304 """ 

305 add = True 

306 for j, va in enumerate(vancestors): 

307 if issubclass(va, a): 

308 add = False 

309 break 

310 if issubclass(a, va): 

311 vancestors[j] = a 

312 add = False 

313 if add: 

314 vancestors.append(a) 

315 

316 

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

318def dispatch_on(*dispatch_args): 

319 """ 

320 Factory of decorators turning a function into a generic function 

321 dispatching on the given arguments. 

322 """ 

323 assert dispatch_args, 'No dispatch args passed' 

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

325 

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

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

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

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

330 (len(dispatch_args), len(arguments), msg)) 

331 

332 def gen_func_dec(func): 

333 """Decorator turning a function into a generic function""" 

334 

335 # first check the dispatch arguments 

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

337 if not set(dispatch_args) <= argset: 

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

339 

340 typemap = {} 

341 

342 def vancestors(*types): 

343 """ 

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

345 """ 

346 check(types) 

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

348 for types_ in typemap: 

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

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

351 append(type_, ra) 

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

353 

354 def ancestors(*types): 

355 """ 

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

357 """ 

358 check(types) 

359 lists = [] 

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

361 n_vas = len(vas) 

362 if n_vas > 1: 

363 raise RuntimeError( 

364 'Ambiguous dispatch for %s: %s' % (t, vas)) 

365 elif n_vas == 1: 

366 va, = vas 

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

368 else: 

369 mro = t.mro() 

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

371 return lists 

372 

373 def register(*types): 

374 """ 

375 Decorator to register an implementation for the given types 

376 """ 

377 check(types) 

378 

379 def dec(f): 

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

381 typemap[types] = f 

382 return f 

383 return dec 

384 

385 def dispatch_info(*types): 

386 """ 

387 An utility to introspect the dispatch algorithm 

388 """ 

389 check(types) 

390 lst = [] 

391 for anc in itertools.product(*ancestors(*types)): 

392 lst.append(tuple(a.__name__ for a in anc)) 

393 return lst 

394 

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

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

397 try: # fast path 

398 f = typemap[types] 

399 except KeyError: 

400 pass 

401 else: 

402 return f(*args, **kw) 

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

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

405 for types_ in combinations: 

406 f = typemap.get(types_) 

407 if f is not None: 

408 return f(*args, **kw) 

409 

410 # else call the default implementation 

411 return func(*args, **kw) 

412 

413 return FunctionMaker.create( 

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

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

416 typemap=typemap, vancestors=vancestors, ancestors=ancestors, 

417 dispatch_info=dispatch_info, __wrapped__=func) 

418 

419 gen_func_dec.__name__ = 'dispatch_on' + dispatch_str 

420 return gen_func_dec