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