Decorate a function to only allow it to be called once.

  Note that it doesn't make sense to only call a function once if it takes
  arguments (use @functools.lru_cache for that sort of thing), so this only
  works on callables that take no args.
550896
def call_once(func):
  
  argspec = inspect.getargspec(func)
  if argspec.args or argspec.varargs or argspec.keywords:
    raise ValueError('Can only decorate functions with no args', func, argspec)

  @functools.wraps(func)
  def _wrapper():
    # If we haven't been called yet, actually invoke func and save the result.
    if not _wrapper.HasRun():
      _wrapper.MarkAsRun()
      _wrapper.return_value = func()
    return _wrapper.return_value

  _wrapper.has_run = False
  _wrapper.HasRun = lambda: _wrapper.has_run
  _wrapper.MarkAsRun = lambda: setattr(_wrapper, 'has_run', True)
  return _wrapper
37101
def prevent_recursion(default):
    """"""
    def decorator(func):
        name = '_calling_%s_' % func.__name__

        def newfunc(self, *args, **kwds):
            if getattr(self, name, False):
                return default()
            setattr(self, name, True)
            try:
                return func(self, *args, **kwds)
            finally:
                setattr(self, name, False)
        return newfunc
    return decorator
433249
def decorate_callable(self, func):
        
        def wrapper(*args, **kwargs):
            try:
                with self:
                    result = func(*args, **kwargs)
                return result
            except DBMutexError as e:
                if self.suppress_acquisition_exceptions:
                    LOG.error(e)
                else:
                    raise e
        functools.update_wrapper(wrapper, func)
        return wrapper
232080
def memoized_method(func):
    

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        self = args[0]
        assert func.__name__ in dir(self), "memoized_method can only be used on method!"

        if not hasattr(self, '_MEMOIZED_CACHE'):
            cache = self._MEMOIZED_CACHE = {}
        else:
            cache = self._MEMOIZED_CACHE

        key = (func, ) + args[1:] + tuple(kwargs)
        ret = cache.get(key, None)
        if ret is not None:
            return ret
        value = func(*args, **kwargs)
        cache[key] = value
        return value

    return wrapper
597877
def cached_method(func):
    
    @functools.wraps(func)
    def wrapper(self, *args):
        if not hasattr(self, "_cache"):
            self._cache = {}
        key = _argstring((func.__name__,) + args)
        if key not in self._cache:
            self._cache[key] = func(self, *args)
        return self._cache[key]
    return wrapper
1049628
def wraps(function):
    """"""
    def wrap(decorator):
        decorator = functools.wraps(function)(decorator)
        if not hasattr(function, 'original'):
            decorator.original = function
        else:
            decorator.original = function.original
            delattr(function, 'original')
        return decorator
    return wrap
702125
function wrapify(fn, before = noop, after = noop) {
  return function(...args) {
    before.call(this);
    var ret = fn.call(this, ...args);
    after.call(this);
    return ret;
  };
}
92129
function makeFunctionWrapper(original, functionName) {
  //log("wrap fn: " + functionName);
  var f = original[functionName];
  return function() {
    //log("call: " + functionName);
    var result = f.apply(original, arguments);
    return result;
  };
}
549951
def decorator(d):
    
    defaults = d.__defaults__
    if defaults and defaults[0] is None:
        # Can be applied as @decorator or @decorator(kwargs) because
        # first argument is None
        def decorate(fn=None, **kwargs):
            if fn is None:
                return _functools.partial(decorate, **kwargs)
            else:
                decorated = d(fn, **kwargs)
                _functools.update_wrapper(decorated, fn)
                return decorated
    else:
        # Can only be applied as @decorator
        def decorate(fn):
            decorated = d(fn)
            _functools.update_wrapper(decorated, fn)
            return decorated
    _functools.update_wrapper(decorate, d)
    return decorate
169628
def _already_decorated_with_invariants(func: CallableT) -> bool:
    """"""
    already_decorated = False
    for a_decorator in _walk_decorator_stack(func=func):
        if getattr(a_decorator, "__is_invariant_check__", False):
            already_decorated = True
            break

    return already_decorated
369636
def use(self, func, when='whenever'):
        '''  '''
        #NOTE A middleware Object ?
        # self.use() is usually called from initialize(), so no logger yet
        print('registering middleware {}'.format(func.__name__))
        self.middlewares.append({
            'call': func,
            'name': func.__name__,
            'args': func.func_code.co_varnames,
            'when': when
        })
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
91771
def decorate_function(self, name, decorator):
        
        self.functions[name] = decorator(self.functions[name])
701101
def dont_cache():
    
    def decorate_func(func):
        @wraps(func)
        def decorate_func_call(*a, **kw):
            callback = SetCacheControlHeadersForNoCachingCallback()
            registry_provider = AfterThisRequestCallbackRegistryProvider()
            registry = registry_provider.provide()
            registry.add(callback)
            return func(*a, **kw)
        return decorate_func_call
    return decorate_func
649190
def once(self, event: str, *handlers: T.Callable) -> T.Callable:
        """"""

        def _once_wrapper(*handlers: T.Callable) -> T.Callable:
            """Wrapper for 'once' decorator"""

            def _wrapper(*args: T.Any, **kw: T.Any) -> None:
                """Wrapper that unregisters itself before executing
                the handlers"""

                self.off(event, _wrapper)
                for handler in handlers:
                    handler(*args, **kw)

            return _wrapper

        if handlers:
            return self.on(event, _once_wrapper(*handlers))
        return lambda x: self.on(event, _once_wrapper(x))
82355
def memoized(func):
    
    cache = {}
    @wraps(func)
    def memoized_function(*args):
        """The decorated function.
        """
        try:
            return cache[args]
        except KeyError:
            value = func(*args)
            try:
                cache[args] = value
            except MemoryError:
                cache.clear()
                gc.collect()
            return value
    return memoized_function
221747
def memoize(func):
    
    cache = {}

    @functools.wraps(func)
    def wrapper(*args):
        key = "__".join(str(arg) for arg in args)
        if key not in cache:
            cache[key] = func(*args)
        return cache[key]
    return wrapper