Return function decorator that executes the function again in case of a deadlock.
497284
def retry_on_deadlock(session, retries=6, min_wait=0.1, max_wait=10.0):
    """"""

    def decorator(action):
        """Function decorator that retries `action` in case of a deadlock."""

        @wraps(action)
        def f(*args, **kwargs):
            num_failures = 0
            while True:
                try:
                    return action(*args, **kwargs)
                except (DBAPIError, DBSerializationError) as e:
                    num_failures += 1
                    is_serialization_error = (
                        isinstance(e, DBSerializationError)
                        or get_db_error_code(e.orig) in DEADLOCK_ERROR_CODES
                    )
                    if num_failures > retries or not is_serialization_error:
                        raise
                session.rollback()
                wait_seconds = min(max_wait, min_wait * 2 ** (num_failures - 1))
                time.sleep(wait_seconds)

        return f

    return decorator
1294233
def wraps(self, f):
        
        @_utils.wraps(f)
        def wrapped_f(*args, **kw):
            return self.call(f, *args, **kw)

        def retry_with(*args, **kwargs):
            return self.copy(*args, **kwargs).wraps(f)

        wrapped_f.retry = self
        wrapped_f.retry_with = retry_with

        return wrapped_f
1251524
def async_(fn):
    """"""
    @functools.wraps(fn)
    async def wrapper(*args, **kwargs):
        return await fn(*args, **kwargs)
    return wrapper
171403
def ensure_async(function_original):
    

    def wrapper(*args, **kwargs):
        try:
            result = function_original(*args, **kwargs)
            if isinstance(result, Deferred):
                return result
            d = Deferred()
            d.callback(result)
            return d
        except:
            return fail()

    return wrapper
1295358
def retry(default=None):
    """"""

    def decorator(func):
        """Retry decorator"""

        @functools.wraps(func)
        def _wrapper(*args, **kw):
            for pos in range(1, MAX_RETRIES):
                try:
                    return func(*args, **kw)
                except (RuntimeError, requests.ConnectionError) as error:
                    LOGGER.warning("Failed: %s, %s", type(error), error)

                # Wait a bit before retrying
                for _ in range(pos):
                    _rest()

            LOGGER.warning("Request Aborted")
            return default

        return _wrapper

    return decorator
1351141
def singleton(func):
    

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        if wrapper.__call_state__ == CALLED:
            return
        ret = func(*args, **kwargs)
        wrapper.__call_state__ = CALLED
        return ret

    def reset():
        wrapper.__call_state__ = NOT_CALLED

    wrapper.reset = reset
    reset()

    # save original func to be able to patch and restore multiple times from
    # unit tests
    wrapper.__original_func = func
    return wrapper
1069749
def auto_retry(fun):
    """"""

    @functools.wraps(fun)
    def decorated(instance, *args, **kwargs):
        """Wrapper around a decorated function."""
        cfg = instance._retry_config
        remaining_tries = cfg.retry_attempts
        current_wait = cfg.retry_wait
        retry_backoff = cfg.retry_backoff
        last_error = None

        while remaining_tries >= 0:
            try:
                return fun(instance, *args, **kwargs)
            except socket.error as e:
                last_error = e
                instance._retry_logger.warning('Connection failed: %s', e)

            remaining_tries -= 1
            if remaining_tries == 0:
                # Last attempt
                break

            # Wait a bit
            time.sleep(current_wait)
            current_wait *= retry_backoff

        # All attempts failed, let's raise the last error.
        raise last_error

    return decorated
957229
def _async_callable(func):
    """"""
    if isinstance(func, types.CoroutineType):

        return func

    @functools.wraps(func)
    async def _async_def_wrapper(*args, **kwargs):
        """Wrap a a sync callable in an async def."""
        return func(*args, **kwargs)

    return _async_def_wrapper
1106265
def synchronized(sync_lock):
    """"""

    def wrapper(f):
        """The decorator's core function.

        :param f:
        :return:
        """

        @functools.wraps(f)
        def inner_wrapper(*args, **kw):
            """

            :param args:
            :param kw:
            :return:
            """
            with sync_lock:
                return f(*args, **kw)

        return inner_wrapper

    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
1329552
def ensure_connected(f):
        
        @functools.wraps(f)
        def wrapper(*args):
            self = args[0]
            self.invalid()
            try:
                return f(*args)
            finally:
                self.invalid()
        return wrapper
865995
def maybe_wait(func):
    
    def wrapper(self, *args, **kwargs):
        if self.slow:
            time.sleep(random.randint(5, 15))
        return func(self, *args, **kwargs)

    return wrapper
862328
def avoid_parallel_execution(func):
    
    def func_wrapper(*args, **kwargs):
        if not getattr(func, "currently_executing", False):
            func.currently_executing = True
            try:
                return func(*args, **kwargs)
            finally:
                func.currently_executing = False
        else:
            logger.verbose("Avoid parallel execution of function {}".format(func))
    return func_wrapper
33852
def wrap(self, func, delay=0):
        '''
        
        '''
        def wrapped():
            self.start()
            if delay:
                self.sleep(delay)
            x = None
            try:
                x = func()
            except OSError as oserror:
                log.debug('OSError exception:%s', oserror)
                self.oserror = oserror
                raise EasyProcessError(self, 'wrap error!')
            finally:
                self.stop()
            return x
        return wrapped
911037
def wait_for(func):
    

    def wrapped(*args, **kwargs):
        timeout = kwargs.pop('timeout', 15)

        start = time()
        result = None

        while time() - start < timeout:
            result = func(*args, **kwargs)
            if result:
                break
            sleep(0.2)

        return result

    return wrapped
1170204
def wrap_function(self, func):
        

        def f(*args, **kwds):
            self.enable_by_count()
            try:
                result = func(*args, **kwds)
            finally:
                self.disable_by_count()
            return result
        return f
1105155
def none_returns(func):
    

    @functools.wraps(func)
    def _execute(*args, **kwargs):
        """Executes function, if error returns None else value of function

        :param args: args of function
        :param kwargs: extra args of function
        :param *args: args
        :param **kwargs: extra args
        :return: None else value of function
        """

        try:
            return func(*args, **kwargs)
        except:
            return None

    return _execute