Python six.wraps() Examples
The following are 30
code examples of six.wraps().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
six
, or try the search function
.
Example #1
Source File: nova.py From manila with Apache License 2.0 | 6 votes |
def translate_server_exception(method): """Transforms the exception for the instance. Note: keeps its traceback intact. """ @six.wraps(method) def wrapper(self, ctx, instance_id, *args, **kwargs): try: res = method(self, ctx, instance_id, *args, **kwargs) return res except nova_exception.ClientException as e: if isinstance(e, nova_exception.NotFound): raise exception.InstanceNotFound(instance_id=instance_id) elif isinstance(e, nova_exception.BadRequest): raise exception.InvalidInput(reason=six.text_type(e)) else: raise exception.ManilaException(e) return wrapper
Example #2
Source File: periodics.py From futurist with Apache License 2.0 | 6 votes |
def _add_jitter(max_percent_jitter): """Wraps a existing strategy and adds jitter to it. 0% to 100% of the spacing value will be added to this value to ensure callbacks do not synchronize. """ if max_percent_jitter > 1 or max_percent_jitter < 0: raise ValueError("Invalid 'max_percent_jitter', must be greater or" " equal to 0.0 and less than or equal to 1.0") def wrapper(func): rnd = random.SystemRandom() @six.wraps(func) def decorator(cb, started_at, finished_at, metrics): next_run = func(cb, started_at, finished_at, metrics) how_often = cb._periodic_spacing jitter = how_often * (rnd.random() * max_percent_jitter) return next_run + jitter decorator.__name__ += "_with_jitter" return decorator return wrapper
Example #3
Source File: openshift.py From kubeshift with GNU Lesser General Public License v3.0 | 6 votes |
def template(action): """Handle template actions. .. py:decorator:: template Checks if the kind is 'template' and processes else default processing. """ def decorator(func): @six.wraps(func) def handler(self, obj, namespace=None): apiver, kind, _ = validator.validate(obj) if kind == 'Template': return self._process_template(apiver, kind, action, obj, namespace) else: return func(self, obj, namespace) return handler return decorator
Example #4
Source File: compare.py From privacyidea with GNU Affero General Public License v3.0 | 6 votes |
def negate(func): """ Given a comparison function ``func``, build and return a comparison function that negates the result of ``func``. :param func: a comparison function taking three arguments :return: a comparison function taking three arguments """ @wraps(func) def negated(left, comparator, right): return not func(left, comparator, right) return negated #: This class enumerates all available comparators. #: In order to add a comparator to this module, add a suitable member to COMPARATORS #: and suitable entries to COMPARATOR_FUNCTIONS and COMPARATOR_DESCRIPTIONS.
Example #5
Source File: base.py From kubeshift with GNU Lesser General Public License v3.0 | 6 votes |
def queryapi(version, kind, nsarg=True): """Make Query API. .. py:decorator:: queryapi Creates a named query api. """ def decorator(func): @six.wraps(func) def handler(self, namespace=DEFAULT_NAMESPACE): if not nsarg: namespace = None url = self._generate_url(api_version=version, kind=kind, namespace=namespace) return Query(self, url) return handler return decorator
Example #6
Source File: test_utils.py From keras-vis with MIT License | 6 votes |
def across_data_formats(func): """Function wrapper to run tests on multiple keras data_format and clean up after TensorFlow tests. Args: func: test function to clean up after. Returns: A function wrapping the input function. """ @six.wraps(func) def wrapper(*args, **kwargs): for data_format in {'channels_first', 'channels_last'}: K.set_image_data_format(data_format) func(*args, **kwargs) if K.backend() == 'tensorflow': K.clear_session() tf.reset_default_graph() return wrapper
Example #7
Source File: process_lock.py From fasteners with Apache License 2.0 | 6 votes |
def interprocess_locked(path): """Acquires & releases a interprocess lock around call into decorated function.""" lock = InterProcessLock(path) def decorator(f): @six.wraps(f) def wrapper(*args, **kwargs): with lock: return f(*args, **kwargs) return wrapper return decorator
Example #8
Source File: decorators.py From is-service-up with Apache License 2.0 | 6 votes |
def authenticated(blocking=True): def decorator(f): @wraps(f) def wrapper(*args, **kwargs): user = None auth = request.headers.get('Authorization') if auth and len(auth) >= 7: sid = auth[7:] # 'Bearer ' prefix session = sessions.get(sid) if session and session.get('user_id'): user = get_user(session['user_id']) if user: user.sid = sid if blocking and not user: raise ApiException('unauthorized', status_code=401) res = f(user=user, *args, **kwargs) return res return wrapper return decorator
Example #9
Source File: test_utils.py From DeepLearning_Wavelet-LSTM with MIT License | 6 votes |
def keras_test(func): """Function wrapper to clean up after TensorFlow tests. # Arguments func: test function to clean up after. # Returns A function wrapping the input function. """ @six.wraps(func) def wrapper(*args, **kwargs): output = func(*args, **kwargs) if K.backend() == 'tensorflow': K.clear_session() return output return wrapper
Example #10
Source File: helpers.py From coinbase-python with Apache License 2.0 | 6 votes |
def mock_response(method, uri, data, errors=None, warnings=None, pagination=None): def wrapper(fn): @six.wraps(fn) @hp.activate def inner(*args, **kwargs): body = {'data': data} if errors is not None: body['errors'] = errors if warnings is not None: body['warnings'] = warnings if pagination is not None: body['pagination'] = pagination hp.reset() hp.register_uri(method, re.compile('.*' + uri + '$'), json.dumps(body)) return fn(*args, **kwargs) return inner return wrapper
Example #11
Source File: test_utils.py From DeepLearning_Wavelet-LSTM with MIT License | 6 votes |
def keras_test(func): """Function wrapper to clean up after TensorFlow tests. # Arguments func: test function to clean up after. # Returns A function wrapping the input function. """ @six.wraps(func) def wrapper(*args, **kwargs): output = func(*args, **kwargs) if K.backend() == 'tensorflow': K.clear_session() return output return wrapper
Example #12
Source File: test_utils.py From DeepLearning_Wavelet-LSTM with MIT License | 6 votes |
def keras_test(func): """Function wrapper to clean up after TensorFlow tests. # Arguments func: test function to clean up after. # Returns A function wrapping the input function. """ @six.wraps(func) def wrapper(*args, **kwargs): output = func(*args, **kwargs) if K.backend() == 'tensorflow': K.clear_session() return output return wrapper
Example #13
Source File: test_utils.py From DeepLearning_Wavelet-LSTM with MIT License | 6 votes |
def keras_test(func): """Function wrapper to clean up after TensorFlow tests. # Arguments func: test function to clean up after. # Returns A function wrapping the input function. """ @six.wraps(func) def wrapper(*args, **kwargs): output = func(*args, **kwargs) if K.backend() == 'tensorflow': K.clear_session() return output return wrapper
Example #14
Source File: test_utils.py From DeepLearning_Wavelet-LSTM with MIT License | 6 votes |
def keras_test(func): """Function wrapper to clean up after TensorFlow tests. # Arguments func: test function to clean up after. # Returns A function wrapping the input function. """ @six.wraps(func) def wrapper(*args, **kwargs): output = func(*args, **kwargs) if K.backend() == 'tensorflow': K.clear_session() return output return wrapper
Example #15
Source File: test_utils.py From keras-vis with MIT License | 6 votes |
def skip_backends(backends): """Function wrapper to specify which backends should skip the test. Args: backends: The list of backends to skip. Returns: A function wrapping the input function. """ backends = set(utils.listify(backends)) def decorator(func): @six.wraps(func) def wrapper(*args, **kwargs): if K.backend() in backends: return func(*args, **kwargs) return wrapper return decorator
Example #16
Source File: utils.py From manila with Apache License 2.0 | 6 votes |
def set_timeout(timeout): """Timeout decorator for unit test methods. Use this decorator for tests that are expected to pass in very specific amount of time, not common for all other tests. It can have either big or small value. """ def _decorator(f): @six.wraps(f) def _wrapper(self, *args, **kwargs): self.useFixture(fixtures.Timeout(timeout, gentle=True)) return f(self, *args, **kwargs) return _wrapper return _decorator
Example #17
Source File: utils.py From gnocchi with Apache License 2.0 | 6 votes |
def return_none_on_failure(f): try: # Python 3 fname = f.__qualname__ except AttributeError: fname = f.__name__ @six.wraps(f) def _return_none_on_failure(*args, **kwargs): try: return f(*args, **kwargs) except Exception as e: LOG.critical("Unexpected error while calling %s: %s", fname, e, exc_info=True) return _return_none_on_failure # Retry with exponential backoff for up to 1 minute
Example #18
Source File: config.py From gin-config with Apache License 2.0 | 6 votes |
def _ensure_wrappability(fn): """Make sure `fn` can be wrapped cleanly by functools.wraps.""" # Handle "builtin_function_or_method", "wrapped_descriptor", and # "method-wrapper" types. unwrappable_types = (type(sum), type(object.__init__), type(object.__call__)) if isinstance(fn, unwrappable_types): # pylint: disable=unnecessary-lambda wrappable_fn = lambda *args, **kwargs: fn(*args, **kwargs) wrappable_fn.__name__ = fn.__name__ wrappable_fn.__doc__ = fn.__doc__ wrappable_fn.__module__ = '' # These types have no __module__, sigh. wrappable_fn.__wrapped__ = fn return wrappable_fn # Otherwise we're good to go... return fn
Example #19
Source File: config.py From gin-config with Apache License 2.0 | 6 votes |
def __init__(self, scoped_selector, evaluate): self._scoped_selector = scoped_selector self._evaluate = evaluate scoped_selector_parts = self._scoped_selector.split('/') self._scopes = scoped_selector_parts[:-1] self._selector = scoped_selector_parts[-1] self._configurable = _REGISTRY.get_match(self._selector) if not self._configurable: _raise_unknown_reference_error(self) def reference_decorator(fn): if self._scopes: @six.wraps(fn) def scoping_wrapper(*args, **kwargs): with config_scope(self._scopes): return fn(*args, **kwargs) return scoping_wrapper return fn self._scoped_configurable_fn = _decorate_fn_or_cls( reference_decorator, self.configurable.fn_or_cls, True)
Example #20
Source File: test_utils.py From DeepLearning_Wavelet-LSTM with MIT License | 6 votes |
def keras_test(func): """Function wrapper to clean up after TensorFlow tests. # Arguments func: test function to clean up after. # Returns A function wrapping the input function. """ @six.wraps(func) def wrapper(*args, **kwargs): output = func(*args, **kwargs) if K.backend() == 'tensorflow': K.clear_session() return output return wrapper
Example #21
Source File: test_utils.py From DeepLearning_Wavelet-LSTM with MIT License | 6 votes |
def keras_test(func): """Function wrapper to clean up after TensorFlow tests. # Arguments func: test function to clean up after. # Returns A function wrapping the input function. """ @six.wraps(func) def wrapper(*args, **kwargs): output = func(*args, **kwargs) if K.backend() == 'tensorflow': K.clear_session() return output return wrapper
Example #22
Source File: utils.py From stethoscope with Apache License 2.0 | 6 votes |
def serialized_endpoint(*_callbacks): """Decorator which wraps an endpoint by applying callbacks to the results then serializing to JSON. First, the decorated function is called and must return a `defer.Deferred`. The callbacks supplied to the decorator are then applied followed by any callbacks supplied as keyword arguments to the decorated function. The result is then serialized and returned in the response (with ``Content-Type`` set to ``application/json``). """ def decorator(func): @six.wraps(func) def wrapped(request, *args, **kwargs): callbacks = kwargs.pop('callbacks', []) # logger.debug("in wrapped:\nargs: {!r}\nkwargs: {!r}", args, kwargs) deferred_list = func(*args, **kwargs) for callback in list(_callbacks) + callbacks: deferred_list.addCallback(callback) deferred_list.addCallback(json.dumps, default=stethoscope.utils.json_serialize_datetime) request.setHeader('Content-Type', 'application/json') return deferred_list return wrapped return decorator
Example #23
Source File: auth.py From stethoscope with Apache License 2.0 | 6 votes |
def token_required(self, func=None, callback=None): """Decorator for endpoints which require a verified user.""" # logger.debug("token_required received func={!r}, callback={!r}", func, callback) if func is None: # called with optional arguments; return value will be called without, so pass them through return functools.partial(self.token_required, callback=callback) @six.wraps(func) def decorator(request, *args, **kwargs): userinfo = self.check_token(request) kwargs['userinfo'] = userinfo args = (request,) + args if callback is not None: # logger.debug("calling {!r} with args={!r} and kwargs={!r}", callback, args, kwargs) callback(*args, **kwargs) # logger.debug("calling {!r} with args={!r} and kwargs={!r}", func, args, kwargs) return func(*args, **kwargs) return decorator
Example #24
Source File: utils.py From os-brick with Apache License 2.0 | 6 votes |
def retry(exceptions, interval=1, retries=3, backoff_rate=2): if retries < 1: raise ValueError(_('Retries must be greater than or ' 'equal to 1 (received: %s). ') % retries) def _decorator(f): @six.wraps(f) def _wrapper(*args, **kwargs): r = tenacity.Retrying( before_sleep=tenacity.before_sleep_log(LOG, logging.DEBUG), after=tenacity.after_log(LOG, logging.DEBUG), stop=tenacity.stop_after_attempt(retries), reraise=True, retry=tenacity.retry_if_exception_type(exceptions), wait=tenacity.wait_exponential( multiplier=interval, min=0, exp_base=backoff_rate)) return r.call(f, *args, **kwargs) return _wrapper return _decorator
Example #25
Source File: test_utils.py From DeepLearning_Wavelet-LSTM with MIT License | 6 votes |
def keras_test(func): """Function wrapper to clean up after TensorFlow tests. # Arguments func: test function to clean up after. # Returns A function wrapping the input function. """ @six.wraps(func) def wrapper(*args, **kwargs): output = func(*args, **kwargs) if K.backend() == 'tensorflow': K.clear_session() return output return wrapper
Example #26
Source File: common.py From storops with Apache License 2.0 | 5 votes |
def allow_omit_parentheses(func): @six.wraps(func) def inner(*args, **kwargs): if len(args) == 1 and inspect.isfunction(args[0]): # Decorator are used without parentheses, this # decorator add the the parentheses return func()(*args, **kwargs) else: return func(*args, **kwargs) return inner
Example #27
Source File: waiters.py From futurist with Apache License 2.0 | 5 votes |
def _ensure_eventlet(func): """Decorator that verifies we have the needed eventlet components.""" @six.wraps(func) def wrapper(*args, **kwargs): if not _utils.EVENTLET_AVAILABLE or greenthreading is None: raise RuntimeError('Eventlet is needed to wait on green futures') return func(*args, **kwargs) return wrapper
Example #28
Source File: common.py From storops with Apache License 2.0 | 5 votes |
def singleton(cls, *args, **kwargs): instance = {} @wraps(cls) def wrapper(*args, **kwargs): if cls not in instance: instance[cls] = cls(*args, **kwargs) return instance[cls] return wrapper
Example #29
Source File: periodics.py From futurist with Apache License 2.0 | 5 votes |
def periodic(spacing, run_immediately=False, enabled=True): """Tags a method/function as wanting/able to execute periodically. :param spacing: how often to run the decorated function (required) :type spacing: float/int :param run_immediately: option to specify whether to run immediately or wait until the spacing provided has elapsed before running for the first time :type run_immediately: boolean :param enabled: whether the task is enabled to run :type enabled: boolean """ if spacing <= 0 and enabled: raise ValueError("Periodicity/spacing must be greater than" " zero instead of %s" % spacing) def wrapper(f): f._is_periodic = enabled f._periodic_spacing = spacing f._periodic_run_immediately = run_immediately @six.wraps(f) def decorator(*args, **kwargs): return f(*args, **kwargs) return decorator return wrapper
Example #30
Source File: utils.py From manila with Apache License 2.0 | 5 votes |
def if_notifications_enabled(function): """Calls decorated method only if notifications are enabled.""" @functools.wraps(function) def wrapped(*args, **kwargs): if notifications_enabled(CONF): return function(*args, **kwargs) return DO_NOTHING return wrapped