Debian Codegraph @

wxgeometrie/pylib/decorator.py

raw symbols SCIP
1 # ######################### LICENSE ############################ #
2
3 # Copyright (c) 2005-2020, 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 """
31 Decorator module, see
32 https://github.com/micheles/decorator/blob/master/docs/documentation.md
33 for the documentation.
34 """
35 from __future__ import print_function
36
37 import re
38 import sys
39 import inspect
40 import operator
41 import itertools
42 import collections
43
44 __version__ = '4.4.2'
45
46 if sys.version_info >= (3,):
47 from inspect import getfullargspec
48
49 def get_init(cls):
50 return cls.__init__
51 else:
52 FullArgSpec = collections.namedtuple(
53 'FullArgSpec', 'args varargs varkw defaults '
54 'kwonlyargs kwonlydefaults annotations')
55
56 def getfullargspec(f):
57 "A quick and dirty replacement for getfullargspec for Python 2.X"
58 return FullArgSpec._make(inspect.getargspec(f) + ([], None, {}))
59
60 def get_init(cls):
61 return cls.__init__.__func__
62
63 try:
64 iscoroutinefunction = inspect.iscoroutinefunction
65 except AttributeError:
66 # let's assume there are no coroutine functions in old Python
67 def iscoroutinefunction(f):
68 return False
69 try:
70 from inspect import isgeneratorfunction
71 except ImportError:
72 # assume no generator function in old Python versions
73 def isgeneratorfunction(caller):
74 return False
75
76
77 DEF = re.compile(r'\s*def\s*([_\w][_\w\d]*)\s*\(')
78
79
80 # basic functionality
81 class FunctionMaker(object):
82 """
83 An object with the ability to create functions with a given signature.
84 It has attributes name, doc, module, signature, defaults, dict and
85 methods update and make.
86 """
87
88 # Atomic get-and-increment provided by the GIL
89 _compile_count = itertools.count()
90
91 # make pylint happy
92 args = varargs = varkw = defaults = kwonlyargs = kwonlydefaults = ()
93
94 def __init__(self, func=None, name=None, signature=None,
95 defaults=None, doc=None, module=None, funcdict=None):
96 self.shortsignature = signature
97 if func:
98 # func can be a class or a callable, but not an instance method
99 self.name = func.__name__
100 if self.name == '<lambda>': # small hack for lambda functions
101 self.name = '_lambda_'
102 self.doc = func.__doc__
103 self.module = func.__module__
104 if inspect.isfunction(func):
105 argspec = getfullargspec(func)
106 self.annotations = getattr(func, '__annotations__', {})
107 for a in ('args', 'varargs', 'varkw', 'defaults', 'kwonlyargs',
108 'kwonlydefaults'):
109 setattr(self, a, getattr(argspec, a))
110 for i, arg in enumerate(self.args):
111 setattr(self, 'arg%d' % i, arg)
112 allargs = list(self.args)
113 allshortargs = list(self.args)
114 if self.varargs:
115 allargs.append('*' + self.varargs)
116 allshortargs.append('*' + self.varargs)
117 elif self.kwonlyargs:
118 allargs.append('*') # single star syntax
119 for a in self.kwonlyargs:
120 allargs.append('%s=None' % a)
121 allshortargs.append('%s=%s' % (a, a))
122 if self.varkw:
123 allargs.append('**' + self.varkw)
124 allshortargs.append('**' + self.varkw)
125 self.signature = ', '.join(allargs)
126 self.shortsignature = ', '.join(allshortargs)
127 self.dict = func.__dict__.copy()
128 # func=None happens when decorating a caller
129 if name:
130 self.name = name
131 if signature is not None:
132 self.signature = signature
133 if defaults:
134 self.defaults = defaults
135 if doc:
136 self.doc = doc
137 if module:
138 self.module = module
139 if funcdict:
140 self.dict = funcdict
141 # check existence required attributes
142 assert hasattr(self, 'name')
143 if not hasattr(self, 'signature'):
144 raise TypeError('You are decorating a non function: %s' % func)
145
146 def update(self, func, **kw):
147 "Update the signature of func with the data in self"
148 func.__name__ = self.name
149 func.__doc__ = getattr(self, 'doc', None)
150 func.__dict__ = getattr(self, 'dict', {})
151 func.__defaults__ = self.defaults
152 func.__kwdefaults__ = self.kwonlydefaults or None
153 func.__annotations__ = getattr(self, 'annotations', None)
154 try:
155 frame = sys._getframe(3)
156 except AttributeError: # for IronPython and similar implementations
157 callermodule = '?'
158 else:
159 callermodule = frame.f_globals.get('__name__', '?')
160 func.__module__ = getattr(self, 'module', callermodule)
161 func.__dict__.update(kw)
162
163 def make(self, src_templ, evaldict=None, addsource=False, **attrs):
164 "Make a new function from a given template and update the signature"
165 src = src_templ % vars(self) # expand name and signature
166 evaldict = evaldict or {}
167 mo = DEF.search(src)
168 if mo is None:
169 raise SyntaxError('not a valid function template\n%s' % src)
170 name = mo.group(1) # extract the function name
171 names = set([name] + [arg.strip(' *') for arg in
172 self.shortsignature.split(',')])
173 for n in names:
174 if n in ('_func_', '_call_'):
175 raise NameError('%s is overridden in\n%s' % (n, src))
176
177 if not src.endswith('\n'): # add a newline for old Pythons
178 src += '\n'
179
180 # Ensure each generated function has a unique filename for profilers
181 # (such as cProfile) that depend on the tuple of (<filename>,
182 # <definition line>, <function name>) being unique.
183 filename = '<decorator-gen-%d>' % next(self._compile_count)
184 try:
185 code = compile(src, filename, 'single')
186 exec(code, evaldict)
187 except Exception:
188 print('Error in generated code:', file=sys.stderr)
189 print(src, file=sys.stderr)
190 raise
191 func = evaldict[name]
192 if addsource:
193 attrs['__source__'] = src
194 self.update(func, **attrs)
195 return func
196
197 @classmethod
198 def create(cls, obj, body, evaldict, defaults=None,
199 doc=None, module=None, addsource=True, **attrs):
200 """
201 Create a function from the strings name, signature and body.
202 evaldict is the evaluation dictionary. If addsource is true an
203 attribute __source__ is added to the result. The attributes attrs
204 are added, if any.
205 """
206 if isinstance(obj, str): # "name(signature)"
207 name, rest = obj.strip().split('(', 1)
208 signature = rest[:-1] # strip a right parens
209 func = None
210 else: # a function
211 name = None
212 signature = None
213 func = obj
214 self = cls(func, name, signature, defaults, doc, module)
215 ibody = '\n'.join(' ' + line for line in body.splitlines())
216 caller = evaldict.get('_call_') # when called from `decorate`
217 if caller and iscoroutinefunction(caller):
218 body = ('async def %(name)s(%(signature)s):\n' + ibody).replace(
219 'return', 'return await')
220 else:
221 body = 'def %(name)s(%(signature)s):\n' + ibody
222 return self.make(body, evaldict, addsource, **attrs)
223
224
225 def decorate(func, caller, extras=()):
226 """
227 decorate(func, caller) decorates a function using a caller.
228 If the caller is a generator function, the resulting function
229 will be a generator function.
230 """
231 evaldict = dict(_call_=caller, _func_=func)
232 es = ''
233 for i, extra in enumerate(extras):
234 ex = '_e%d_' % i
235 evaldict[ex] = extra
236 es += ex + ', '
237
238 if '3.5' <= sys.version < '3.6':
239 # with Python 3.5 isgeneratorfunction returns True for all coroutines
240 # however we know that it is NOT possible to have a generator
241 # coroutine in python 3.5: PEP525 was not there yet
242 generatorcaller = isgeneratorfunction(
243 caller) and not iscoroutinefunction(caller)
244 else:
245 generatorcaller = isgeneratorfunction(caller)
246 if generatorcaller:
247 fun = FunctionMaker.create(
248 func, "for res in _call_(_func_, %s%%(shortsignature)s):\n"
249 " yield res" % es, evaldict, __wrapped__=func)
250 else:
251 fun = FunctionMaker.create(
252 func, "return _call_(_func_, %s%%(shortsignature)s)" % es,
253 evaldict, __wrapped__=func)
254 if hasattr(func, '__qualname__'):
255 fun.__qualname__ = func.__qualname__
256 return fun
257
258
259 def decorator(caller, _func=None):
260 """decorator(caller) converts a caller function into a decorator"""
261 if _func is not None: # return a decorated function
262 # this is obsolete behavior; you should use decorate instead
263 return decorate(_func, caller)
264 # else return a decorator function
265 defaultargs, defaults = '', ()
266 if inspect.isclass(caller):
267 name = caller.__name__.lower()
268 doc = 'decorator(%s) converts functions/generators into ' \
269 'factories of %s objects' % (caller.__name__, caller.__name__)
270 elif inspect.isfunction(caller):
271 if caller.__name__ == '<lambda>':
272 name = '_lambda_'
273 else:
274 name = caller.__name__
275 doc = caller.__doc__
276 nargs = caller.__code__.co_argcount
277 ndefs = len(caller.__defaults__ or ())
278 defaultargs = ', '.join(caller.__code__.co_varnames[nargs-ndefs:nargs])
279 if defaultargs:
280 defaultargs += ','
281 defaults = caller.__defaults__
282 else: # assume caller is an object with a __call__ method
283 name = caller.__class__.__name__.lower()
284 doc = caller.__call__.__doc__
285 evaldict = dict(_call=caller, _decorate_=decorate)
286 dec = FunctionMaker.create(
287 '%s(func, %s)' % (name, defaultargs),
288 'if func is None: return lambda func: _decorate_(func, _call, (%s))\n'
289 'return _decorate_(func, _call, (%s))' % (defaultargs, defaultargs),
290 evaldict, doc=doc, module=caller.__module__, __wrapped__=caller)
291 if defaults:
292 dec.__defaults__ = (None,) + defaults
293 return dec
294
295
296 # ####################### contextmanager ####################### #
297
298 try: # Python >= 3.2
299 from contextlib import _GeneratorContextManager
300 except ImportError: # Python >= 2.5
301 from contextlib import GeneratorContextManager as _GeneratorContextManager
302
303
304 class ContextManager(_GeneratorContextManager):
305 def __call__(self, func):
306 """Context manager decorator"""
307 return FunctionMaker.create(
308 func, "with _self_: return _func_(%(shortsignature)s)",
309 dict(_self_=self, _func_=func), __wrapped__=func)
310
311
312 init = getfullargspec(_GeneratorContextManager.__init__)
313 n_args = len(init.args)
314 if n_args == 2 and not init.varargs: # (self, genobj) Python 2.7
315 def __init__(self, g, *a, **k):
316 return _GeneratorContextManager.__init__(self, g(*a, **k))
317 ContextManager.__init__ = __init__
318 elif n_args == 2 and init.varargs: # (self, gen, *a, **k) Python 3.4
319 pass
320 elif n_args == 4: # (self, gen, args, kwds) Python 3.5
321 def __init__(self, g, *a, **k):
322 return _GeneratorContextManager.__init__(self, g, a, k)
323 ContextManager.__init__ = __init__
324
325 _contextmanager = decorator(ContextManager)
326
327
328 def contextmanager(func):
329 # Enable Pylint config: contextmanager-decorators=decorator.contextmanager
330 return _contextmanager(func)
331
332
333 # ############################ dispatch_on ############################ #
334
335 def append(a, vancestors):
336 """
337 Append ``a`` to the list of the virtual ancestors, unless it is already
338 included.
339 """
340 add = True
341 for j, va in enumerate(vancestors):
342 if issubclass(va, a):
343 add = False
344 break
345 if issubclass(a, va):
346 vancestors[j] = a
347 add = False
348 if add:
349 vancestors.append(a)
350
351
352 # inspired from simplegeneric by P.J. Eby and functools.singledispatch
353 def dispatch_on(*dispatch_args):
354 """
355 Factory of decorators turning a function into a generic function
356 dispatching on the given arguments.
357 """
358 assert dispatch_args, 'No dispatch args passed'
359 dispatch_str = '(%s,)' % ', '.join(dispatch_args)
360
361 def check(arguments, wrong=operator.ne, msg=''):
362 """Make sure one passes the expected number of arguments"""
363 if wrong(len(arguments), len(dispatch_args)):
364 raise TypeError('Expected %d arguments, got %d%s' %
365 (len(dispatch_args), len(arguments), msg))
366
367 def gen_func_dec(func):
368 """Decorator turning a function into a generic function"""
369
370 # first check the dispatch arguments
371 argset = set(getfullargspec(func).args)
372 if not set(dispatch_args) <= argset:
373 raise NameError('Unknown dispatch arguments %s' % dispatch_str)
374
375 typemap = {}
376
377 def vancestors(*types):
378 """
379 Get a list of sets of virtual ancestors for the given types
380 """
381 check(types)
382 ras = [[] for _ in range(len(dispatch_args))]
383 for types_ in typemap:
384 for t, type_, ra in zip(types, types_, ras):
385 if issubclass(t, type_) and type_ not in t.mro():
386 append(type_, ra)
387 return [set(ra) for ra in ras]
388
389 def ancestors(*types):
390 """
391 Get a list of virtual MROs, one for each type
392 """
393 check(types)
394 lists = []
395 for t, vas in zip(types, vancestors(*types)):
396 n_vas = len(vas)
397 if n_vas > 1:
398 raise RuntimeError(
399 'Ambiguous dispatch for %s: %s' % (t, vas))
400 elif n_vas == 1:
401 va, = vas
402 mro = type('t', (t, va), {}).mro()[1:]
403 else:
404 mro = t.mro()
405 lists.append(mro[:-1]) # discard t and object
406 return lists
407
408 def register(*types):
409 """
410 Decorator to register an implementation for the given types
411 """
412 check(types)
413
414 def dec(f):
415 check(getfullargspec(f).args, operator.lt, ' in ' + f.__name__)
416 typemap[types] = f
417 return f
418 return dec
419
420 def dispatch_info(*types):
421 """
422 An utility to introspect the dispatch algorithm
423 """
424 check(types)
425 lst = []
426 for anc in itertools.product(*ancestors(*types)):
427 lst.append(tuple(a.__name__ for a in anc))
428 return lst
429
430 def _dispatch(dispatch_args, *args, **kw):
431 types = tuple(type(arg) for arg in dispatch_args)
432 try: # fast path
433 f = typemap[types]
434 except KeyError:
435 pass
436 else:
437 return f(*args, **kw)
438 combinations = itertools.product(*ancestors(*types))
439 next(combinations) # the first one has been already tried
440 for types_ in combinations:
441 f = typemap.get(types_)
442 if f is not None:
443 return f(*args, **kw)
444
445 # else call the default implementation
446 return func(*args, **kw)
447
448 return FunctionMaker.create(
449 func, 'return _f_(%s, %%(shortsignature)s)' % dispatch_str,
450 dict(_f_=_dispatch), register=register, default=func,
451 typemap=typemap, vancestors=vancestors, ancestors=ancestors,
452 dispatch_info=dispatch_info, __wrapped__=func)
453
454 gen_func_dec.__name__ = 'dispatch_on' + dispatch_str
455 return gen_func_dec