Python decorator.decorator() Examples
The following are 30
code examples of decorator.decorator().
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
decorator
, or try the search function
.
Example #1
Source File: validation.py From magnum with Apache License 2.0 | 6 votes |
def enforce_volume_driver_types_update(): @decorator.decorator def wrapper(func, *args, **kwargs): cluster_template_ident = args[1] patch = args[2] cluster_template = api_utils.get_resource('ClusterTemplate', cluster_template_ident) try: cluster_template_dict = api_utils.apply_jsonpatch( cluster_template.as_dict(), patch) except api_utils.JSONPATCH_EXCEPTIONS as e: raise exception.PatchError(patch=patch, reason=e) _enforce_volume_driver_types(cluster_template_dict) return func(*args, **kwargs) return wrapper
Example #2
Source File: decorators.py From ngraph-python with Apache License 2.0 | 6 votes |
def with_error_settings(**new_settings): """ TODO. Arguments: **new_settings: TODO Returns: """ @decorator.decorator def dec(f, *args, **kwargs): old_settings = np.geterr() np.seterr(**new_settings) ret = f(*args, **kwargs) np.seterr(**old_settings) return ret return dec
Example #3
Source File: core.py From jams with ISC License | 6 votes |
def deprecated(version, version_removed): '''This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used.''' def __wrapper(func, *args, **kwargs): '''Warn the user, and then proceed.''' code = six.get_function_code(func) warnings.warn_explicit( "{:s}.{:s}\n\tDeprecated as of JAMS version {:s}." "\n\tIt will be removed in JAMS version {:s}." .format(func.__module__, func.__name__, version, version_removed), category=DeprecationWarning, filename=code.co_filename, lineno=code.co_firstlineno + 1 ) return func(*args, **kwargs) return decorator(__wrapper)
Example #4
Source File: __init__.py From treadmill with Apache License 2.0 | 6 votes |
def _journal(journaler): """Journaler to decorate API functions. """ @decorator.decorator def decorated(func, *args, **kwargs): """Decorated function.""" action = getattr( func, 'journal_action', func.__name__.strip('_')) resource = getattr( func, 'journal_resource', func.__module__.strip('_')) transaction_id = _get_tx_id() journaler.log_begin(transaction_id, resource, action, args) try: result = func(*args, **kwargs) journaler.log_end(transaction_id, resource, action, args, result) except Exception as err: # we log execption of API and raise again journaler.log_abort(transaction_id, resource, action, args, err) raise err return result return decorated
Example #5
Source File: decorators.py From allura with Apache License 2.0 | 6 votes |
def reconfirm_auth(func, *args, **kwargs): ''' A decorator to require the user to reconfirm their login. Useful for sensitive pages. ''' from allura.lib.plugin import AuthenticationProvider if request.POST.get('password'): if AuthenticationProvider.get(request).validate_password(c.user, request.POST['password']): session['auth-reconfirmed'] = datetime.utcnow() session.save() kwargs.pop('password', None) else: c.form_errors['password'] = 'Invalid password.' allowed_timedelta = timedelta(seconds=asint(config.get('auth.reconfirm.seconds', 60))) last_reconfirm = session.get('auth-reconfirmed', datetime.min) if datetime.utcnow() - last_reconfirm <= allowed_timedelta: return func(*args, **kwargs) else: return render({}, 'jinja', "allura:templates/reconfirm_auth.html")
Example #6
Source File: _utils.py From shade with Apache License 2.0 | 6 votes |
def valid_kwargs(*valid_args): # This decorator checks if argument passed as **kwargs to a function are # present in valid_args. # # Typically, valid_kwargs is used when we want to distinguish between # None and omitted arguments and we still want to validate the argument # list. # # Example usage: # # @valid_kwargs('opt_arg1', 'opt_arg2') # def my_func(self, mandatory_arg1, mandatory_arg2, **kwargs): # ... # @decorator def func_wrapper(func, *args, **kwargs): argspec = inspect.getargspec(func) for k in kwargs: if k not in argspec.args[1:] and k not in valid_args: raise TypeError( "{f}() got an unexpected keyword argument " "'{arg}'".format(f=inspect.stack()[1][3], arg=k)) return func(*args, **kwargs) return func_wrapper
Example #7
Source File: core.py From chepy with GNU General Public License v3.0 | 6 votes |
def call_stack(func, *args, **kwargs): """This decorator is used to get the method name and arguments and save it to self.stack. The data from self.stack is predominantly used to save recepies. """ func_sig = dict() func_self = args[0] func_sig["function"] = func.__name__ bound_args = inspect.signature(func).bind(*args, **kwargs) bound_args.apply_defaults() func_arguments = dict(bound_args.arguments) del func_arguments["self"] func_sig["args"] = func_arguments func_self._stack.append(func_sig) return func(*args, **kwargs)
Example #8
Source File: conftest.py From scalyr-agent-2 with Apache License 2.0 | 6 votes |
def submit_result_to_codespeed(func): """ Decorator which marks a pytest benchmark function with "submit_result_to_codespeed" marker. """ # NOTE: functools.wraps doesn't work well enough under Python 2 so we need to use decorator # package def wrapped_function(func, *args, **kwargs): if isinstance(args[0], BenchmarkFixture): benchmark = args[0] elif "benchmark" in kwargs: benchmark = kwargs["benchmark"] else: raise ValueError('Unable to detect "benchmark" kwarg') benchmark.submit_result_to_codespeed = True return func(*args, **kwargs) return decorator.decorator(wrapped_function, func) # Register a custom marker
Example #9
Source File: _utils.py From openstacksdk with Apache License 2.0 | 6 votes |
def valid_kwargs(*valid_args): # This decorator checks if argument passed as **kwargs to a function are # present in valid_args. # # Typically, valid_kwargs is used when we want to distinguish between # None and omitted arguments and we still want to validate the argument # list. # # Example usage: # # @valid_kwargs('opt_arg1', 'opt_arg2') # def my_func(self, mandatory_arg1, mandatory_arg2, **kwargs): # ... # @decorator def func_wrapper(func, *args, **kwargs): argspec = inspect.getargspec(func) for k in kwargs: if k not in argspec.args[1:] and k not in valid_args: raise TypeError( "{f}() got an unexpected keyword argument " "'{arg}'".format(f=inspect.stack()[1][3], arg=k)) return func(*args, **kwargs) return func_wrapper
Example #10
Source File: validation.py From magnum with Apache License 2.0 | 6 votes |
def enforce_driver_supported(): @decorator.decorator def wrapper(func, *args, **kwargs): cluster_template = args[1] cluster_distro = cluster_template.cluster_distro if not cluster_distro: try: cli = clients.OpenStackClients(pecan.request.context) image_id = cluster_template.image_id image = api_utils.get_openstack_resource(cli.glance().images, image_id, 'images') cluster_distro = image.get('os_distro') except Exception: pass cluster_type = (cluster_template.server_type, cluster_distro, cluster_template.coe) driver.Driver.get_driver(*cluster_type) return func(*args, **kwargs) return wrapper
Example #11
Source File: util.py From sklearn-evaluation with MIT License | 6 votes |
def requires_properties(properties): @decorator def _requires_properties(func, *args, **kwargs): params = util.map_parameters_in_fn_call(args, kwargs, func) obj = params.get('self') if obj is None: raise Exception('This decorator only works on instance methods') missing = [p for p in properties if getattr(obj, p) is None] if len(missing): raise ValueError('{} requires {} to be set, missing: {}' .format(func.__name__, properties, missing)) return func(*args, **kwargs) return _requires_properties
Example #12
Source File: policy.py From magnum with Apache License 2.0 | 6 votes |
def enforce_wsgi(api_name, act=None): """This is a decorator to simplify wsgi action policy rule check. :param api_name: The collection name to be evaluate. :param act: The function name of wsgi action. example: from magnum.common import policy class ClustersController(rest.RestController): .... @policy.enforce_wsgi("cluster", "delete") @wsme_pecan.wsexpose(None, types.uuid_or_name, status_code=204) def delete(self, cluster_ident): ... """ @decorator.decorator def wrapper(fn, *args, **kwargs): action = "%s:%s" % (api_name, (act or fn.__name__)) enforce(pecan.request.context, action, exc=exception.PolicyNotAuthorized, action=action) return fn(*args, **kwargs) return wrapper
Example #13
Source File: utils.py From elasticintel with GNU General Public License v3.0 | 5 votes |
def validator(func, *args, **kwargs): """ A decorator that makes given function validator. Whenever the given function is called and returns ``False`` value this decorator returns :class:`ValidationFailure` object. Example:: >>> @validator ... def even(value): ... return not (value % 2) >>> even(4) True >>> even(5) ValidationFailure(func=even, args={'value': 5}) :param func: function to decorate :param args: positional function arguments :param kwargs: key value function arguments """ def wrapper(func, *args, **kwargs): value = func(*args, **kwargs) if not value: return ValidationFailure( func, func_args_as_dict(func, args, kwargs) ) return True return decorator(wrapper, func)
Example #14
Source File: _utils.py From shade with Apache License 2.0 | 5 votes |
def _func_wrap(f): # NOTE(morgan): This extra wrapper is intended to eliminate ever # passing a bound method to dogpile.cache's cache_on_arguments. In # 0.7.0 and later it is impossible to pass bound methods to the # decorator. This was introduced when utilizing the decorate module in # lieu of a direct wrap implementation. @functools.wraps(f) def inner(*args, **kwargs): return f(*args, **kwargs) return inner
Example #15
Source File: decorators.py From devito with MIT License | 5 votes |
def __call__(self, f): def wrapper(f, *args, **kwargs): from devito.parameters import configuration if configuration["develop-mode"]: self.nargs = f.__code__.co_argcount self.defaults = f.__defaults__ or () self.varnames = f.__code__.co_varnames self.file = f.__code__.co_filename self.line = f.__code__.co_firstlineno + 1 self.check_args(args, kwargs) return f(*args, **kwargs) return decorator(wrapper, f)
Example #16
Source File: action.py From qiime2 with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _get_async_wrapper(self): def async_wrapper(*args, **kwargs): # TODO handle this better in the future, but stop the massive error # caused by MacOSX asynchronous runs for now. try: import matplotlib as plt if plt.rcParams['backend'].lower() == 'macosx': raise EnvironmentError(backend_error_template % plt.matplotlib_fname()) except ImportError: pass # This function's signature is rewritten below using # `decorator.decorator`. When the signature is rewritten, args[0] # is the function whose signature was used to rewrite this # function's signature. args = args[1:] pool = concurrent.futures.ProcessPoolExecutor(max_workers=1) future = pool.submit(_subprocess_apply, self, args, kwargs) # TODO: pool.shutdown(wait=False) caused the child process to # hang unrecoverably. This seems to be a bug in Python 3.7 # It's probably best to gut concurrent.futures entirely, so we're # ignoring the resource leakage for the moment. return future async_wrapper = self._rewrite_wrapper_signature(async_wrapper) self._set_wrapper_properties(async_wrapper) self._set_wrapper_name(async_wrapper, 'asynchronous') return async_wrapper
Example #17
Source File: cliutils.py From python-magnumclient with Apache License 2.0 | 5 votes |
def deprecated(message): """Decorator for marking a call as deprecated by printing a given message. Example: >>> @deprecated("Bay functions are deprecated and should be replaced by " ... "calls to cluster") ... def bay_create(args): ... pass """ @decorator.decorator def wrapper(func, *args, **kwargs): print(message) return func(*args, **kwargs) return wrapper
Example #18
Source File: decorators.py From rtv with MIT License | 5 votes |
def deprecated(msg=''): """Deprecate decorated method.""" @decorator.decorator def wrap(function, *args, **kwargs): if not kwargs.pop('disable_warning', False): warn(msg, DeprecationWarning) return function(*args, **kwargs) return wrap
Example #19
Source File: common.py From luscan-devel with GNU General Public License v2.0 | 5 votes |
def decorator(w): """ The decorator module was not found. You can install it from: http://pypi.python.org/pypi/decorator/ """ def d(fn): @functools.wraps(fn) def x(*args, **kwargs): return w(fn, *args, **kwargs) return x return d
Example #20
Source File: _utils.py From openstacksdk with Apache License 2.0 | 5 votes |
def _func_wrap(f): # NOTE(morgan): This extra wrapper is intended to eliminate ever # passing a bound method to dogpile.cache's cache_on_arguments. In # 0.7.0 and later it is impossible to pass bound methods to the # decorator. This was introduced when utilizing the decorate module in # lieu of a direct wrap implementation. @functools.wraps(f) def inner(*args, **kwargs): return f(*args, **kwargs) return inner
Example #21
Source File: cliutils.py From python-magnumclient with Apache License 2.0 | 5 votes |
def add_arg(func, *args, **kwargs): """Bind CLI arguments to a shell.py `do_foo` function.""" if not hasattr(func, 'arguments'): func.arguments = [] # NOTE(sirp): avoid dups that can occur when the module is shared across # tests. if (args, kwargs) not in func.arguments: # Because of the semantics of decorator composition if we just append # to the options list positional options will appear to be backwards. func.arguments.insert(0, (args, kwargs))
Example #22
Source File: cliutils.py From python-magnumclient with Apache License 2.0 | 5 votes |
def isunauthenticated(func): """Checks if the function does not require authentication. Mark such functions with the `@unauthenticated` decorator. :returns: bool """ return getattr(func, 'unauthenticated', False)
Example #23
Source File: keywordgroup.py From robotframework-appiumlibrary with Apache License 2.0 | 5 votes |
def __new__(cls, clsname, bases, dict): if decorator: for name, method in dict.items(): if not name.startswith('_') and inspect.isroutine(method): dict[name] = decorator(_run_on_failure_decorator, method) return type.__new__(cls, clsname, bases, dict)
Example #24
Source File: decorators.py From ttrv with MIT License | 5 votes |
def require_captcha(function, *args, **kwargs): """Return a decorator for methods that require captchas.""" raise_captcha_exception = kwargs.pop('raise_captcha_exception', False) captcha_id = None # Get a handle to the reddit session if hasattr(args[0], 'reddit_session'): reddit_session = args[0].reddit_session else: reddit_session = args[0] while True: try: if captcha_id: captcha_answer = _get_captcha(reddit_session, captcha_id) # When the method is being decorated, all of its default # parameters become part of this *args tuple. This means that # *args currently contains a None where the captcha answer # needs to go. If we put the captcha in the **kwargs, # we get a TypeError for having two values of the same param. func_args = _make_func_args(function) if 'captcha' in func_args: captcha_index = func_args.index('captcha') args = list(args) args[captcha_index] = captcha_answer else: kwargs['captcha'] = captcha_answer return function(*args, **kwargs) except errors.InvalidCaptcha as exception: if raise_captcha_exception or \ not hasattr(sys.stdin, 'closed') or sys.stdin.closed: raise captcha_id = exception.response['captcha']
Example #25
Source File: decorators.py From ttrv with MIT License | 5 votes |
def deprecated(msg=''): """Deprecate decorated method.""" @decorator.decorator def wrap(function, *args, **kwargs): if not kwargs.pop('disable_warning', False): warn(msg, DeprecationWarning) return function(*args, **kwargs) return wrap
Example #26
Source File: decorators.py From ttrv with MIT License | 5 votes |
def alias_function(function, class_name): """Create a RedditContentObject function mapped to a BaseReddit function. The BaseReddit classes define the majority of the API's functions. The first argument for many of these functions is the RedditContentObject that they operate on. This factory returns functions appropriate to be called on a RedditContent object that maps to the corresponding BaseReddit function. """ @wraps(function) def wrapped(self, *args, **kwargs): func_args = _make_func_args(function) if 'subreddit' in func_args and func_args.index('subreddit') != 1: # Only happens for search kwargs['subreddit'] = self return function(self.reddit_session, *args, **kwargs) else: return function(self.reddit_session, self, *args, **kwargs) # Only grab the short-line doc and add a link to the complete doc if wrapped.__doc__ is not None: wrapped.__doc__ = wrapped.__doc__.split('\n', 1)[0] wrapped.__doc__ += ('\n\nSee :meth:`.{0}.{1}` for complete usage. ' 'Note that you should exclude the subreddit ' 'parameter when calling this convenience method.' .format(class_name, function.__name__)) # Don't hide from sphinx as this is a parameter modifying decorator return wrapped
Example #27
Source File: keywordgroup.py From robotframework-anywherelibrary with MIT License | 5 votes |
def __new__(cls, clsname, bases, dict): if decorator: for name, method in dict.items(): if not name.startswith('_') and inspect.isroutine(method): dict[name] = decorator(_run_on_failure_decorator, method) return type.__new__(cls, clsname, bases, dict)
Example #28
Source File: decorators.py From rtv with MIT License | 5 votes |
def alias_function(function, class_name): """Create a RedditContentObject function mapped to a BaseReddit function. The BaseReddit classes define the majority of the API's functions. The first argument for many of these functions is the RedditContentObject that they operate on. This factory returns functions appropriate to be called on a RedditContent object that maps to the corresponding BaseReddit function. """ @wraps(function) def wrapped(self, *args, **kwargs): func_args = _make_func_args(function) if 'subreddit' in func_args and func_args.index('subreddit') != 1: # Only happens for search kwargs['subreddit'] = self return function(self.reddit_session, *args, **kwargs) else: return function(self.reddit_session, self, *args, **kwargs) # Only grab the short-line doc and add a link to the complete doc if wrapped.__doc__ is not None: wrapped.__doc__ = wrapped.__doc__.split('\n', 1)[0] wrapped.__doc__ += ('\n\nSee :meth:`.{0}.{1}` for complete usage. ' 'Note that you should exclude the subreddit ' 'parameter when calling this convenience method.' .format(class_name, function.__name__)) # Don't hide from sphinx as this is a parameter modifying decorator return wrapped
Example #29
Source File: base.py From omniduct with MIT License | 5 votes |
def render_statement(method, self, statement, *args, **kwargs): """ Pre-render a statement template prior to wrapped function execution. This decorator expects to act as wrapper on functions which takes statements as the second argument. """ if kwargs.pop('template', True): statement = self.template_render( statement, context=kwargs.pop('context', {}), by_name=False, ) return method(self, statement, *args, **kwargs)
Example #30
Source File: action.py From qiime2 with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _rewrite_wrapper_signature(self, wrapper): # Convert the callable's signature into the wrapper's signature and set # it on the wrapper. return decorator.decorator( wrapper, self._callable_sig_converter_(self._callable))