Memorizes a function or a class decorator
176028
def _onDecorator(self, name, line, pos, absPosition):
        """"""
        # A class or a function must be on the top of the stack
        d = Decorator(name, line, pos, absPosition)
        if self.__lastDecorators is None:
            self.__lastDecorators = [d]
        else:
            self.__lastDecorators.append(d)
488372
def memoize(func):
    """"""
    cache = {}

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        """Caching wrapper."""
        key = (args, tuple(sorted(kwargs.items())))
        if key in cache:
            return cache[key]
        else:
            result = func(*args, **kwargs)
            cache[key] = result
            return result

    return wrapper
1334580
def setonce(decorator):
    """"""
    def decorate(fn, *args, **kwargs):
        parent = decorator(fn, *args, **kwargs)
        #doc = _add_msg(getattr(parent, '__doc__', None), '*@setonce*')
        doc = getattr(parent, '__doc__', None)
        assert hasattr(parent, "__set__") # don't use for non-data descriptors!
        return _setonce(fn.__name__, parent, doc)
    return decorate
1197838
def cache(cls, func):
        

        @functools.wraps(func)
        def func_wrapper(*args, **kwargs):
            func_key = cls.get_key(func)
            val_cache = cls.get_cache(func_key)
            lock = cls.get_cache_lock(func_key)

            return cls._get_value_from_cache(
                func, val_cache, lock, *args, **kwargs)

        return func_wrapper
690245
def memoize(func):
    '''
    
    '''
    cache = {}

    @wraps(func)
    def _memoize(*args, **kwargs):
        str_args = []
        for arg in args:
            if not isinstance(arg, six.string_types):
                str_args.append(six.text_type(arg))
            else:
                str_args.append(arg)

        args_ = ','.join(list(str_args) + ['{0}={1}'.format(k, kwargs[k]) for k in sorted(kwargs)])
        if args_ not in cache:
            cache[args_] = func(*args, **kwargs)
        return cache[args_]

    return _memoize
221249
def good_classmethod_decorator(decorator):
    """""" 
    def new_decorator(cls, f):
        g = decorator(cls, f)
        g.__name__ = f.__name__
        g.__doc__ = f.__doc__
        g.__dict__.update(f.__dict__)
        return g
        
    new_decorator.__name__ = decorator.__name__
    new_decorator.__doc__ = decorator.__doc__
    new_decorator.__dict__.update(decorator.__dict__)

    return new_decorator
1212195
def call_decorator(cls, func):
        

        @wraps(func)
        def _wrap(self, *args, **kwargs):
            try:
                return func(self, *args, **kwargs)
            except Exception:
                self.logger.exception('While executing benchmark')
                if not (self.catch_child_exception or False):
                    raise

        return _wrap
1333919
def memoize(func):
  
  class Memoizer(dict):
    def __missing__(self, args):
      val = func(*args)
      self[args] = val
      return val
  memory = Memoizer()
  @wraps(func)
  def wrapper(*args):
    return memory[args]
  return wrapper
1263190
def memoize_methodcalls(func, pickle=False, dumps=pickle.dumps):
    '''
    '''
    cache = func._memoize_cache = {}
    @functools.wraps(func)
    def memoizer(self, *args, **kwargs):
        if pickle:
            key = dumps((args, kwargs))
        else:
            key = args
        if key not in cache:
            cache[key] = func(self, *args, **kwargs)
        return cache[key]
    return memoizer
348633
def decorator(self, func):
        
        if inspect.isfunction(func):
            func._methodview = self
        elif inspect.ismethod(func):
            func.__func__._methodview = self
        else:
            raise AssertionError('Can only decorate function and methods, {} given'.format(func))
        return func
91771
def decorate_function(self, name, decorator):
        
        self.functions[name] = decorator(self.functions[name])
1280502
def _memo(f):
    """"""
    memos = {}
    def memoized(*args):
        try: return memos[args]
        except KeyError:
            result = memos[args] = f(*args)
            return result
    return memoized
389137
def memoize_single_argument(f):
    
    class memodict(dict):

        def __missing__(self, key):
            ret = self[key] = f(key)
            return ret
    return memodict().__getitem__
53184
def lru_cache(fn):
    '''
    
    '''
    @wraps(fn)
    def memoized_fn(*args):
        pargs = pickle.dumps(args)
        if pargs not in memoized_fn.cache:
            memoized_fn.cache[pargs] = fn(*args)
        return memoized_fn.cache[pargs]
    # propagate function attributes in the event that
    # this is applied as a function and not a decorator
    for attr, value in iter(fn.__dict__.items()):
        setattr(memoized_fn, attr, value)
    memoized_fn.cache = {}
    return memoized_fn
6317
def memoize(f):
    
    class memodict(dict):

        def __getitem__(self, *key):
            return dict.__getitem__(self, key)

        def __missing__(self, key):
            ret = self[key] = f(*key)
            return ret

    return memodict().__getitem__
389086
def trace(_name):
    
    def decorator(_func):
        """This is the actual decorator function that wraps the
        \var{_func} function for detailed logging.
        """

        def positional(name, value):
            """Format one named positional argument.
            """
            if name is __self:
                return af_self(name, value)
            elif name is __klass:
                return af_class(name, value)
            else:
                return af_named(name, value)

        def wrapper(*__argv, **__kwds):
            if not logger.isEnabledFor(logging.DEBUG) or _.value:
                return _func(*__argv, **__kwds)

            try:
                _.value = True
                params = dict(co_defaults)
                params.update(__kwds)
                params.update(zip(co_varnames, __argv))
                if 'raw_password' in params:
                    params['raw_password'] = '<censored>'

                position = [
                    positional(n, params.pop(n))
                    for n in co_varnames[:len(__argv)]
                ]
                defaults = [
                    af_default(n, params.pop(n))
                    for n in co_varnames[len(__argv):]
                ]
                nameless = (
                    af_unnamed(v) for v in __argv[co_argcount:]
                )
                keywords = (
                    af_keyword(n, params[n]) for n in sorted(params.keys())
                )

                params = ', '.join(
                    filter(None, chain(
                        position,
                        defaults,
                        nameless,
                        keywords)))
                # params = params.replace(', [', '[, ').replace('][, ', ', ')

                enter = [pre_enter]
                if params:
                    enter.append(' ')
                    enter.append(params)
                    enter.append(' ')
                enter.append(')')

                leave = [pre_leave]

                try:
                    logger.debug(''.join(enter))
                    try:
                        try:
                            _.value = False
                            result = _func(*__argv, **__kwds)
                        finally:
                            _.value = True
                    except Exception:
                        ex_type, value, traceback = sys.exc_info()
                        leave.append(' => exception thrown\n\traise ')
                        __mname = ex_type.__module__
                        if __mname != '__main__':
                            leave.append(__mname)
                            leave.append('.')
                        leave.append(ex_type.__name__)
                        if value.args:
                            leave.append('(')
                            leave.append(
                                ', '.join(chop(v) for v in value.args))
                            leave.append(')')
                        else:
                            leave.append('()')
                        raise
                    else:
                        if result is not None:
                            leave.append(' => ')
                            leave.append(chop(result))
                finally:
                    logger.debug(''.join(leave))
            finally:
                _.value = False

            return result

        ####
        #  decorator
        ####

        __self = False
        __klass = False

        def nop(x):
            return x

        __rewrap = nop
        if type(_func) in FunctionTypes:
            # functions do not belong to a class.
            __cname = None
        elif type(_func) in MethodTypes:
            # im_self is None for unbound instance methods.
            # Assumption: trace is only called on unbound methods.
            if _func.im_self is not None:
                __rewrap = classmethod
                __cname = _func.im_self.__name__
                __klass = True
            else:
                __cname = _func.im_class.__name__
                __self = True
            _func = _func.im_func
        else:
            # other callables are not supported yet.
            return _func
        __module = _func.__module__
        __fname = _func.__name__

        # Do not wrap initialization and conversion methods.
        if __fname in ('__init__', '__new__', '__repr__', '__str__'):
            return __rewrap(_func)

        # Generate the Fully Qualified Function Name.

        __fqfn = list()
        if __module != '__main__':
            __fqfn.append(__module)
            __fqfn.append('.')
        if __cname is not None:
            __fqfn.append(__cname)
            __fqfn.append('.')
        __fqfn.append(__fname)
        __fqfn = ''.join(__fqfn)

        if type(_name) in CallableTypes:
            logger = get_logger_factory().get_logger(__fqfn)
        elif loggable(_name):
            logger = _name
        elif isinstance(_name, six.string_types):
            logger = get_logger_factory().get_logger(_name)
        else:
            raise ValueError(
                'invalid object %r: must be a function, a method, '
                'a string or an object that implements the Logger API' % _name)

        pre_enter = ['>>> ', __fqfn, '(']
        pre_enter = ''.join(pre_enter)

        pre_leave = ['<<< ', __fqfn]
        pre_leave = ''.join(pre_leave)

        ####
        #  Here we are really mucking around in function internals.
        #  func_code is the low level 'code' instance that describes
        #  the function arguments, variable and other stuff.
        #
        #  func.func_code.co_argcount - number of function arguments.
        #  func.func_code.co_varnames - function variables names, the
        #      first co_argcount values are the argument names.
        #  func.func_defaults - contains default arguments

        try:
            code = _func.__code__
        except AttributeError:
            co_argcount, co_varnames, co_defaults = \
                __lookup_builtin(_func.__name__)
        else:
            co_argcount = code.co_argcount
            co_varnames = code.co_varnames[:co_argcount]
            if _func.__defaults__:
                co_defaults = dict(
                    zip(co_varnames[-len(_func.__defaults__):],
                        _func.__defaults__))
            else:
                co_defaults = dict()
            if __klass:
                __klass = co_varnames[0]
            if __self:
                __self = co_varnames[0]
        return __rewrap(wraps(_func)(wrapper))

    ####
    #  trace
    ####

#    logging.basicConfig(level = logging.DEBUG)
    if type(_name) in CallableTypes:
        return decorator(_name)
    else:
        return decorator
414234
def dual_use_decorator(fn):
    """"""
    @functools.wraps(fn)
    def decorator(*args, **kw):
        if len(args) == 1 and not kw and callable(args[0]):
            return fn()(args[0])
        else:
            return fn(*args, **kw)
    return decorator