Python functools.wraps() Examples
The following are 30
code examples of functools.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
functools
, or try the search function
.

Example #1
Source File: utils.py From quart with MIT License | 8 votes |
def run_sync(func: Callable[..., Any]) -> Callable[..., Coroutine[Any, None, None]]: """Ensure that the sync function is run within the event loop. If the *func* is not a coroutine it will be wrapped such that it runs in the default executor (use loop.set_default_executor to change). This ensures that synchronous functions do not block the event loop. """ @wraps(func) async def _wrapper(*args: Any, **kwargs: Any) -> Any: loop = asyncio.get_running_loop() result = await loop.run_in_executor( None, copy_context().run, partial(func, *args, **kwargs) ) if isgenerator(result): return run_sync_iterable(result) # type: ignore else: return result _wrapper._quart_async_wrapper = True # type: ignore return _wrapper
Example #2
Source File: module_utils.py From audio with BSD 2-Clause "Simplified" License | 7 votes |
def requires_module(*modules: str): """Decorate function to give error message if invoked without required optional modules. This decorator is to give better error message to users rather than raising ``NameError: name 'module' is not defined`` at random places. """ missing = [m for m in modules if not is_module_available(m)] if not missing: # fall through. If all the modules are available, no need to decorate def decorator(func): return func else: req = f'module: {missing[0]}' if len(missing) == 1 else f'modules: {missing}' def decorator(func): @wraps(func) def wrapped(*args, **kwargs): raise RuntimeError(f'{func.__module__}.{func.__name__} requires {req}') return wrapped return decorator
Example #3
Source File: module_utils.py From audio with BSD 2-Clause "Simplified" License | 6 votes |
def deprecated(direction: str, version: Optional[str] = None): """Decorator to add deprecation message Args: direction: Migration steps to be given to users. """ def decorator(func): @wraps(func) def wrapped(*args, **kwargs): message = ( f'{func.__module__}.{func.__name__} has been deprecated ' f'and will be removed from {"future" if version is None else version} release.' f'{direction}') warnings.warn(message, stacklevel=2) return func(*args, **kwargs) return wrapped return decorator
Example #4
Source File: decorators.py From aegea with Apache License 2.0 | 6 votes |
def requires_app_credentials(func): """Require client_id and client_secret to be associated. This is used to note and enforce which methods require a client_id and client_secret to be used. """ @wraps(func) def auth_wrapper(self, *args, **kwargs): client_id, client_secret = self._session.retrieve_client_credentials() if client_id and client_secret: return func(self, *args, **kwargs) else: from .models import GitHubError # Mock a 401 response r = generate_fake_error_response( '{"message": "Requires username/password authentication"}' ) raise GitHubError(r) return auth_wrapper
Example #5
Source File: decorators.py From aegea with Apache License 2.0 | 6 votes |
def requires_basic_auth(func): """Specific (basic) authentication decorator. This is used to note which object methods require username/password authorization and won't work with token based authorization. """ @wraps(func) def auth_wrapper(self, *args, **kwargs): if hasattr(self, '_session') and self._session.auth: return func(self, *args, **kwargs) else: from .models import GitHubError # Mock a 401 response r = generate_fake_error_response( '{"message": "Requires username/password authentication"}' ) raise GitHubError(r) return auth_wrapper
Example #6
Source File: file_utils.py From cmrc2019 with Creative Commons Attribution Share Alike 4.0 International | 6 votes |
def s3_request(func: Callable): """ Wrapper function for s3 requests in order to create more helpful error messages. """ @wraps(func) def wrapper(url: str, *args, **kwargs): try: return func(url, *args, **kwargs) except ClientError as exc: if int(exc.response["Error"]["Code"]) == 404: raise FileNotFoundError("file {} not found".format(url)) else: raise return wrapper
Example #7
Source File: api_helpers.py From everyclass-server with Mozilla Public License 2.0 | 6 votes |
def token_required(func): """ 检查是否携带token,如果token未携带或无效将直接返回错误,否则将username保存到g.username中 """ from everyclass.server.user import service as user_service @functools.wraps(func) def wrapped(*args, **kwargs): token = request.headers.get("X-API-Token") if not token: return generate_error_response(None, STATUS_CODE_TOKEN_MISSING) username = user_service.get_username_from_jwt(token) if not username: return generate_error_response(None, STATUS_CODE_INVALID_TOKEN) g.username = username return func(*args, **kwargs) return wrapped
Example #8
Source File: api_helpers.py From everyclass-server with Mozilla Public License 2.0 | 6 votes |
def login_required(func): """检查用户是否已登录,如未登录则返回错误""" @functools.wraps(func) def wrapped(*args, **kwargs): try: ut, uid = get_ut_uid() if ut == UTYPE_GUEST: return generate_error_response(None, STATUS_CODE_PERMISSION_DENIED, "您需要登录才能进行此操作") except NotImplementedError: return generate_error_response(None, STATUS_CODE_PERMISSION_DENIED, "检测身份时遇到未知错误") g.user_id = uid return func(*args, **kwargs) return wrapped
Example #9
Source File: decorators.py From aegea with Apache License 2.0 | 6 votes |
def requires_auth(func): """Decorator to note which object methods require authorization.""" @wraps(func) def auth_wrapper(self, *args, **kwargs): auth = False if hasattr(self, '_session'): auth = (self._session.auth or self._session.headers.get('Authorization')) if auth: return func(self, *args, **kwargs) else: from .models import GitHubError # Mock a 401 response r = generate_fake_error_response( '{"message": "Requires authentication"}' ) raise GitHubError(r) return auth_wrapper
Example #10
Source File: flask_pyoidc.py From Flask-pyoidc with Apache License 2.0 | 6 votes |
def oidc_logout(self, view_func): self._logout_view = view_func @functools.wraps(view_func) def wrapper(*args, **kwargs): if 'state' in flask.request.args: # returning redirect from provider if flask.request.args['state'] != flask.session.pop('end_session_state'): logger.error("Got unexpected state '%s' after logout redirect.", flask.request.args['state']) return view_func(*args, **kwargs) redirect_to_provider = self._logout() if redirect_to_provider: return redirect_to_provider return view_func(*args, **kwargs) return wrapper
Example #11
Source File: auth.py From eve-auth-jwt with MIT License | 6 votes |
def requires_token(self, audiences=None, allowed_roles=None): """ Decorator for functions that will be protected with token authentication. Token must be provvided either through access_token parameter or Authorization header. See check_token() method for further details. """ def requires_token_wrapper(f): @wraps(f) def decorated(*args, **kwargs): try: token = request.args['access_token'] except KeyError: token = request.headers.get('Authorization', '').partition(' ')[2] if not self._perform_verification(token, audiences, allowed_roles): abort(401) return f(*args, **kwargs) return decorated return requires_token_wrapper
Example #12
Source File: discover.py From multibootusb with GNU General Public License v2.0 | 6 votes |
def wrap_exception(func): """ Allow Device discovery methods to return None instead of raising an exception. """ @functools.wraps(func) def the_func(*args, **kwargs): """ Returns result of calling ``func`` on ``args``, ``kwargs``. Returns None if ``func`` raises :exc:`DeviceNotFoundError`. """ try: return func(*args, **kwargs) except DeviceNotFoundError: return None return the_func
Example #13
Source File: loader.py From friendly-telegram with GNU Affero General Public License v3.0 | 6 votes |
def translateable_docstring(cls): @functools.wraps(cls.config_complete) def config_complete(self, *args, **kwargs): for command, func in get_commands(cls).items(): @functools.wraps(func) def replacement(*args, **kwargs): return func(self, *args, **kwargs) replacement.__doc__ = self.strings["_cmd_doc_" + command] setattr(self, command, replacement) self.__doc__ = self.strings["_cls_doc"] return self.config_complete._old_(self, *args, **kwargs) config_complete._old_ = cls.config_complete cls.config_complete = config_complete for command, func in get_commands(cls).items(): cls.strings["_cmd_doc_" + command] = inspect.getdoc(func) cls.strings["_cls_doc"] = inspect.getdoc(cls) return cls
Example #14
Source File: decorators.py From comport with BSD 3-Clause "New" or "Revised" License | 6 votes |
def extractor_auth_required(): ''' Ensures that current_user is an extractor with access to the correct department ''' def check_extractor(view_function): @wraps(view_function) def decorated_function(*args, **kwargs): username = request.authorization.username password = request.authorization.password found_extractor = Extractor.query.filter_by(username=username).first() if not found_extractor: return ("No extractor with that username!", 401) if not found_extractor.check_password(password): return ("Extractor authorization failed!", 401) return view_function(*args, **kwargs) return decorated_function return check_extractor
Example #15
Source File: scopes.py From DOTA_models with Apache License 2.0 | 6 votes |
def add_arg_scope(func): """Decorates a function with args so it can be used within an arg_scope. Args: func: function to decorate. Returns: A tuple with the decorated function func_with_args(). """ @functools.wraps(func) def func_with_args(*args, **kwargs): current_scope = _current_arg_scope() current_args = kwargs key_func = (func.__module__, func.__name__) if key_func in current_scope: current_args = current_scope[key_func].copy() current_args.update(kwargs) return func(*args, **current_args) _add_op(func) return func_with_args
Example #16
Source File: _compat_test.py From OpenFermion-Cirq with Apache License 2.0 | 6 votes |
def deprecated_test(test: Callable) -> Callable: """Marks a test as using deprecated functionality. Ensures the test is executed within the `pytest.deprecated_call()` context. Args: test: The test. Returns: The decorated test. """ @functools.wraps(test) def decorated_test(*args, **kwargs) -> Any: with pytest.deprecated_call(): test(*args, **kwargs) return decorated_test
Example #17
Source File: cache.py From ssm-cache-python with MIT License | 6 votes |
def refresh_on_error( self, error_class=Exception, error_callback=None, retry_argument='is_retry' ): """ Decorator to handle errors and retries """ if error_callback and not callable(error_callback): raise TypeError("error_callback must be callable") def true_decorator(func): """ Actual func wrapper """ @wraps(func) def wrapped(*args, **kwargs): """ Actual error/retry handling """ try: return func(*args, **kwargs) except error_class: # pylint: disable=broad-except self.refresh() if error_callback: error_callback() if retry_argument: kwargs[retry_argument] = True return func(*args, **kwargs) return wrapped return true_decorator
Example #18
Source File: utils.py From PickTrue with MIT License | 6 votes |
def retry(max_retries=3): def wrapper(func): @wraps(func) def wrapped(*args, **kwargs): retries = 0 while retries <= max_retries: retries += 1 try: return func(*args, **kwargs) except Exception: if retries > max_retries: download_logger.exception("Error occurs while execute function\n") break time.sleep(1) return None return wrapped return wrapper
Example #19
Source File: tools.py From iqfeed with Apache License 2.0 | 6 votes |
def retry(tries, exceptions=None, delay=0): """ Decorator for retrying a function if exception occurs Source: https://gist.github.com/treo/728327 tries -- num tries exceptions -- exceptions to catch delay -- wait between retries """ exceptions_ = exceptions or (Exception, ) def _retry(fn): @wraps(fn) def __retry(*args, **kwargs): for _ in range(tries+1): try: return fn(*args, **kwargs) except exceptions_ as e: log.warning("Exception, retrying...", exc_info=e) time.sleep(delay) raise # If no success after tries raise last exception return __retry return _retry
Example #20
Source File: auth.py From Paradrop with Apache License 2.0 | 6 votes |
def requires_auth(func): """ Use as a decorator for API functions to require authorization. This checks the Authorization HTTP header. It handles username and password as well as bearer tokens. """ @functools.wraps(func) def decorated(self, request, *args, **kwargs): if not check_auth(request, self.password_manager, self.token_manager): out.info('HTTP {} {} {} {}'.format(request.getClientIP(), request.method, request.path, 401)) request.setResponseCode(401) request.setHeader("WWW-Authenticate", "Basic realm=\"Login Required\"") return return func(self, request, *args, **kwargs) return decorated
Example #21
Source File: expert_utils.py From fine-lm with MIT License | 6 votes |
def add_scope(scope=None, scope_fn=None): """Return a decorator which add a TF name/variable scope to a function. Note that the function returned by the decorator accept an additional 'name' parameter, which can overwrite the name scope given when the function is created. Args: scope (str): name of the scope. If None, the function name is used. scope_fn (fct): Either tf.name_scope or tf.variable_scope Returns: fct: the add_scope decorator """ def decorator(f): @functools.wraps(f) def decorated(*args, **kwargs): name = kwargs.pop("name", None) # Python 2 hack for keyword only args with scope_fn(name or scope or f.__name__): return f(*args, **kwargs) return decorated return decorator
Example #22
Source File: common_layers.py From fine-lm with MIT License | 6 votes |
def recompute_grad(fn): """Decorator that recomputes the function on the backwards pass. Args: fn: a function that takes Tensors (all as positional arguments) and returns a tuple of Tensors. Returns: A wrapped fn that is identical to fn when called, but its activations will be discarded and recomputed on the backwards pass (i.e. on a call to tf.gradients). """ @functools.wraps(fn) def wrapped(*args): return _recompute_grad(fn, args) return wrapped
Example #23
Source File: util.py From lirpg with MIT License | 6 votes |
def store_args(method): """Stores provided method args as instance attributes. """ argspec = inspect.getfullargspec(method) defaults = {} if argspec.defaults is not None: defaults = dict( zip(argspec.args[-len(argspec.defaults):], argspec.defaults)) if argspec.kwonlydefaults is not None: defaults.update(argspec.kwonlydefaults) arg_names = argspec.args[1:] @functools.wraps(method) def wrapper(*positional_args, **keyword_args): self = positional_args[0] # Get default arg values args = defaults.copy() # Add provided arg values for name, value in zip(arg_names, positional_args[1:]): args[name] = value args.update(keyword_args) self.__dict__.update(args) return method(*positional_args, **keyword_args) return wrapper
Example #24
Source File: formatters.py From jupyterlab_code_formatter with MIT License | 6 votes |
def handle_line_ending_and_magic(func): @wraps(func) def wrapped(self, code: str, notebook: bool, **options) -> str: has_semicolon = code.strip().endswith(";") code = re.sub(MAGIC_COMMAND_RE, "# %#", code) code = func(self, code, notebook, **options) code = re.sub(COMMENTED_MAGIC_COMMAND_RE, "%", code) if notebook: code = code.rstrip() if has_semicolon and notebook: code += ";" return code return wrapped
Example #25
Source File: toolbox.py From xalpha with MIT License | 6 votes |
def error_catcher(f): """ 装饰器,透明捕获 DateMismatch :param f: :return: """ @wraps(f) def wrapper(*args, **kws): try: return f(*args, **kws) except DateMismatch as e: code = args[0] error_msg = e.reason error_msg += ", therefore %s cannot predict correctly" % code raise NonAccurate(code=code, reason=error_msg) return wrapper
Example #26
Source File: provider.py From xalpha with MIT License | 6 votes |
def data_source(s): """ 用以强制要求某些数据源已注册的装饰器。 :param s: 数据源,现在仅支持 "jq" :return: """ def protected(f): @wraps(f) def wrapper(*args, **kws): if getattr(thismodule, s + "_auth", False): return f(*args, **kws) else: raise DataSourceNotFound("Data source %s is not authenticated" % s) return wrapper return protected
Example #27
Source File: decorators.py From comport with BSD 3-Clause "New" or "Revised" License | 6 votes |
def requires_roles(required_roles): ''' Takes in a list of roles and checks whether the user has access to those role ''' def check_roles(view_function): @wraps(view_function) def decorated_function(*args, **kwargs): def names(role): return role.name if not all(r in map(names, current_user.roles) for r in required_roles): flash('You do not have sufficient permissions to do that', 'alert alert-danger') return redirect(request.args.get('next') or '/') return view_function(*args, **kwargs) return decorated_function return check_roles
Example #28
Source File: policy.py From drydock with Apache License 2.0 | 5 votes |
def __call__(self, f): @functools.wraps(f) def secure_handler(slf, req, resp, *args, **kwargs): ctx = req.context policy_engine = ctx.policy_engine self.logger.debug("Enforcing policy %s on request %s" % (self.action, ctx.request_id)) if policy_engine is not None and policy_engine.authorize( self.action, ctx): return f(slf, req, resp, *args, **kwargs) else: if ctx.authenticated: slf.info( ctx, "Error - Forbidden access - action: %s" % self.action) slf.return_error( resp, falcon.HTTP_403, message="Forbidden", retry=False) else: slf.info(ctx, "Error - Unauthenticated access") slf.return_error( resp, falcon.HTTP_401, message="Unauthenticated", retry=False) return secure_handler
Example #29
Source File: tf_util.py From lirpg with MIT License | 5 votes |
def in_session(f): @functools.wraps(f) def newfunc(*args, **kwargs): with tf.Session(): f(*args, **kwargs) return newfunc
Example #30
Source File: hook.py From apm-python-agent-principle with MIT License | 5 votes |
def func_wrapper(func): @functools.wraps(func) def wrapper(*args, **kwargs): print('start func') start = time.time() result = func(*args, **kwargs) end = time.time() print('spent {}s'.format(end - start)) return result return wrapper