python类decorator()的实例源码

handler.py 文件源码 项目:twisted-json-rpc 作者: elston 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def as_view(path):
    def decorator(func):
        # ..
        path_name, klass_name  = (path.split(':'))
        # ...
        @inlineCallbacks
        def wrapper(router, request, *args, **kwargs):
            # ...
            module = importlib.import_module(path_name)
            Klass = getattr(module,klass_name)
            klass = Klass(router, request,*args, **kwargs)
            # ..
            result = yield defer.maybeDeferred(klass)            
            defer.returnValue(result)
        # ..
        # _conspect_name(wrapper, klass_name)
        _conspect_name(wrapper, func.__name__)        
        _conspect_param(wrapper, func)
        _conspect_param_defaults(wrapper, func)        
        return wrapper
    return decorator
decorators.py 文件源码 项目:ngraph 作者: NervanaSystems 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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
application.py 文件源码 项目:leetcode 作者: thomasyimgit 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def catch_config_error(method, app, *args, **kwargs):
    """Method decorator for catching invalid config (Trait/ArgumentErrors) during init.

    On a TraitError (generally caused by bad config), this will print the trait's
    message, and exit the app.

    For use on init methods, to prevent invoking excepthook on invalid input.
    """
    try:
        return method(app, *args, **kwargs)
    except (TraitError, ArgumentError) as e:
        app.print_help()
        app.log.fatal("Bad config encountered during initialization:")
        app.log.fatal(str(e))
        app.log.debug("Config at the time: %s", app.config)
        app.exit(1)
magic.py 文件源码 项目:leetcode 作者: thomasyimgit 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def magics_class(cls):
    """Class decorator for all subclasses of the main Magics class.

    Any class that subclasses Magics *must* also apply this decorator, to
    ensure that all the methods that have been decorated as line/cell magics
    get correctly registered in the class instance.  This is necessary because
    when method decorators run, the class does not exist yet, so they
    temporarily store their information into a module global.  Application of
    this class decorator copies that global data to the class instance and
    clears the global.

    Obviously, this mechanism is not thread-safe, which means that the
    *creation* of subclasses of Magic should only be done in a single-thread
    context.  Instantiation of the classes has no restrictions.  Given that
    these classes are typically created at IPython startup time and before user
    application code becomes active, in practice this should not pose any
    problems.
    """
    cls.registered = True
    cls.magics = dict(line = magics['line'],
                      cell = magics['cell'])
    magics['line'] = {}
    magics['cell'] = {}
    return cls
decorators.py 文件源码 项目:leetcode 作者: thomasyimgit 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def skip(msg=None):
    """Decorator factory - mark a test function for skipping from test suite.

    Parameters
    ----------
      msg : string
        Optional message to be added.

    Returns
    -------
       decorator : function
         Decorator, which, when applied to a function, causes SkipTest
         to be raised, with the optional message added.
      """

    return skipif(True,msg)
authentication.py 文件源码 项目:of 作者: OptimalBPM 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def check_session_aspect(func, *args, **kwargs):
    """
    The authentication aspect code, provides an aspect for the aop_check_session decorator

    """

    # Get a list of the names of the non-keyword arguments
    _argument_specifications = getfullargspec(func)
    try:
        # Try and find _session_id
        arg_idx = _argument_specifications.args.index("_session_id")
    except:
        raise Exception("Authentication aspect for \"" + func.__name__ + "\": No _session_id parameter")

    # Check if the session is valid.
    _user = check_session(args[arg_idx])

    # Call the function and set the _user parameter, if existing.
    return alter_function_parameter_and_call(func, args, kwargs, '_user', _user)
decorators.py 文件源码 项目:PYEdit 作者: Congren 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def preprocess_args(fun,varnames):
    """ Applies fun to variables in varnames before launching the function """

    def wrapper(f, *a, **kw):
        if hasattr(f, "func_code"):
            func_code = f.func_code # Python 2
        else:
            func_code = f.__code__ # Python 3

        names = func_code.co_varnames
        new_a = [fun(arg) if (name in varnames) else arg
                 for (arg, name) in zip(a, names)]
        new_kw = {k: fun(v) if k in varnames else v
                 for (k,v) in kw.items()}
        return f(*new_a, **new_kw)
    return decorator.decorator(wrapper)
application.py 文件源码 项目:Repobot 作者: Desgard 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def catch_config_error(method, app, *args, **kwargs):
    """Method decorator for catching invalid config (Trait/ArgumentErrors) during init.

    On a TraitError (generally caused by bad config), this will print the trait's
    message, and exit the app.

    For use on init methods, to prevent invoking excepthook on invalid input.
    """
    try:
        return method(app, *args, **kwargs)
    except (TraitError, ArgumentError) as e:
        app.print_help()
        app.log.fatal("Bad config encountered during initialization:")
        app.log.fatal(str(e))
        app.log.debug("Config at the time: %s", app.config)
        app.exit(1)
magic.py 文件源码 项目:Repobot 作者: Desgard 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def magics_class(cls):
    """Class decorator for all subclasses of the main Magics class.

    Any class that subclasses Magics *must* also apply this decorator, to
    ensure that all the methods that have been decorated as line/cell magics
    get correctly registered in the class instance.  This is necessary because
    when method decorators run, the class does not exist yet, so they
    temporarily store their information into a module global.  Application of
    this class decorator copies that global data to the class instance and
    clears the global.

    Obviously, this mechanism is not thread-safe, which means that the
    *creation* of subclasses of Magic should only be done in a single-thread
    context.  Instantiation of the classes has no restrictions.  Given that
    these classes are typically created at IPython startup time and before user
    application code becomes active, in practice this should not pose any
    problems.
    """
    cls.registered = True
    cls.magics = dict(line = magics['line'],
                      cell = magics['cell'])
    magics['line'] = {}
    magics['cell'] = {}
    return cls
decorators.py 文件源码 项目:Repobot 作者: Desgard 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def skip(msg=None):
    """Decorator factory - mark a test function for skipping from test suite.

    Parameters
    ----------
      msg : string
        Optional message to be added.

    Returns
    -------
       decorator : function
         Decorator, which, when applied to a function, causes SkipTest
         to be raised, with the optional message added.
      """

    return skipif(True,msg)
format.py 文件源码 项目:pymake 作者: dtrckd 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def _name(cls, l):
        if getattr(cls, '_alias', None):
            _alias =  cls._alias
        else:
            return l


        if isinstance(l, (set, list, tuple)):
            return [ _alias.get(i, i) for i in l ]
        elif isinstance(l, (dict, ExpSpace)):
            d = dict(l)
            for k, v in d.items():
                if isinstance(v, basestring) and v in _alias:
                    d[k] = _alias[v]
            return d
        else :
            return _alias.get(l, l)


### Todo:
#  try to read the decorator that were called for _[post|pre]process
# * if @plot then display
# * if @tabulate then ...
format.py 文件源码 项目:pymake 作者: dtrckd 项目源码 文件源码 阅读 40 收藏 0 点赞 0 评论 0
def tabulate(*groups):
        ''' TODO
        '''
        if len(groups[1:]) == 0 and callable(groups[0]):
            # decorator whithout arguments
            return groups[0]
        else:
            row = groups[0]
            column = groups[1]
            def decorator(fun):
                @wraps(fun)
                def wrapper(*args, **kwargs):
                    kernel = fun(*args, **kwargs)
                    return kernel
                return wrapper
        return decorator
decorators.py 文件源码 项目:CartoonPy 作者: bxtkezhan 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def preprocess_args(fun, varnames):
    """ Applies fun to variables in varnames before launching the function """

    def wrapper(f, *a, **kw):
        """ MPOCode.
        if hasattr(f, "func_code"):
            func_code = f.func_code  # Python 2
        else:
            func_code = f.__code__  # Python 3
        """
        func_code = f.__code__ 

        names = func_code.co_varnames
        new_a = [
            fun(arg) if (name in varnames) else arg
            for (arg, name) in zip(a, names)
        ]
        new_kw = {k: fun(v) if k in varnames else v for (k, v) in kw.items()}
        return f(*new_a, **new_kw)

    return decorator.decorator(wrapper)
decorators.py 文件源码 项目:CartoonPy 作者: bxtkezhan 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def preprocess_args(fun, varnames):
    """ Applies fun to variables in varnames before launching the function """

    def wrapper(f, *a, **kw):
        """ MPOCode.
        if hasattr(f, "func_code"):
            func_code = f.func_code  # Python 2
        else:
            func_code = f.__code__  # Python 3
        """
        func_code = f.__code__ 

        names = func_code.co_varnames
        new_a = [
            fun(arg) if (name in varnames) else arg
            for (arg, name) in zip(a, names)
        ]
        new_kw = {k: fun(v) if k in varnames else v for (k, v) in kw.items()}
        return f(*new_a, **new_kw)

    return decorator.decorator(wrapper)
decorator.py 文件源码 项目:neurotools 作者: michaelerule 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def memoize(f):
    '''
    Memoization decorator

    Parameters
    ----------

    Returns
    -------
    '''
    cache = {}
    info  = defaultdict(dict)
    @robust_decorator
    def wrapped(f,*args,**kwargs):
        sig = argument_signature(f,*args,**kwargs)
        if not sig in cache:
            time,result = f(*args,**kwargs)
            info[sig]['density'] = time/sys.getsizeof(result)
            cache[sig] = result
        return cache[sig]
    wrapped.__cache__ = cache
    wrapped.__info__  = info
    return wrapped(timed(f))
application.py 文件源码 项目:blender 作者: gastrodia 项目源码 文件源码 阅读 41 收藏 0 点赞 0 评论 0
def catch_config_error(method, app, *args, **kwargs):
    """Method decorator for catching invalid config (Trait/ArgumentErrors) during init.

    On a TraitError (generally caused by bad config), this will print the trait's
    message, and exit the app.

    For use on init methods, to prevent invoking excepthook on invalid input.
    """
    try:
        return method(app, *args, **kwargs)
    except (TraitError, ArgumentError) as e:
        app.print_help()
        app.log.fatal("Bad config encountered during initialization:")
        app.log.fatal(str(e))
        app.log.debug("Config at the time: %s", app.config)
        app.exit(1)
magic.py 文件源码 项目:blender 作者: gastrodia 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def magics_class(cls):
    """Class decorator for all subclasses of the main Magics class.

    Any class that subclasses Magics *must* also apply this decorator, to
    ensure that all the methods that have been decorated as line/cell magics
    get correctly registered in the class instance.  This is necessary because
    when method decorators run, the class does not exist yet, so they
    temporarily store their information into a module global.  Application of
    this class decorator copies that global data to the class instance and
    clears the global.

    Obviously, this mechanism is not thread-safe, which means that the
    *creation* of subclasses of Magic should only be done in a single-thread
    context.  Instantiation of the classes has no restrictions.  Given that
    these classes are typically created at IPython startup time and before user
    application code becomes active, in practice this should not pose any
    problems.
    """
    cls.registered = True
    cls.magics = dict(line = magics['line'],
                      cell = magics['cell'])
    magics['line'] = {}
    magics['cell'] = {}
    return cls
decorators.py 文件源码 项目:blender 作者: gastrodia 项目源码 文件源码 阅读 45 收藏 0 点赞 0 评论 0
def skip(msg=None):
    """Decorator factory - mark a test function for skipping from test suite.

    Parameters
    ----------
      msg : string
        Optional message to be added.

    Returns
    -------
       decorator : function
         Decorator, which, when applied to a function, causes SkipTest
         to be raised, with the optional message added.
      """

    return skipif(True,msg)
utils.py 文件源码 项目:adjutant 作者: openstack 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def require_roles(roles, func, *args, **kwargs):
    """
    endpoints setup with this decorator require the defined roles.
    """
    request = args[1]
    req_roles = set(roles)
    if not request.keystone_user.get('authenticated', False):
        return Response({'errors': ["Credentials incorrect or none given."]},
                        401)

    roles = set(request.keystone_user.get('roles', []))

    if roles & req_roles:
        return func(*args, **kwargs)

    return Response({'errors': ["Must have one of the following roles: %s" %
                                list(req_roles)]}, 403)
application.py 文件源码 项目:yatta_reader 作者: sound88 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def catch_config_error(method, app, *args, **kwargs):
    """Method decorator for catching invalid config (Trait/ArgumentErrors) during init.

    On a TraitError (generally caused by bad config), this will print the trait's
    message, and exit the app.

    For use on init methods, to prevent invoking excepthook on invalid input.
    """
    try:
        return method(app, *args, **kwargs)
    except (TraitError, ArgumentError) as e:
        app.print_help()
        app.log.fatal("Bad config encountered during initialization:")
        app.log.fatal(str(e))
        app.log.debug("Config at the time: %s", app.config)
        app.exit(1)
magic.py 文件源码 项目:yatta_reader 作者: sound88 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def magics_class(cls):
    """Class decorator for all subclasses of the main Magics class.

    Any class that subclasses Magics *must* also apply this decorator, to
    ensure that all the methods that have been decorated as line/cell magics
    get correctly registered in the class instance.  This is necessary because
    when method decorators run, the class does not exist yet, so they
    temporarily store their information into a module global.  Application of
    this class decorator copies that global data to the class instance and
    clears the global.

    Obviously, this mechanism is not thread-safe, which means that the
    *creation* of subclasses of Magic should only be done in a single-thread
    context.  Instantiation of the classes has no restrictions.  Given that
    these classes are typically created at IPython startup time and before user
    application code becomes active, in practice this should not pose any
    problems.
    """
    cls.registered = True
    cls.magics = dict(line = magics['line'],
                      cell = magics['cell'])
    magics['line'] = {}
    magics['cell'] = {}
    return cls
decorators.py 文件源码 项目:yatta_reader 作者: sound88 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def skip(msg=None):
    """Decorator factory - mark a test function for skipping from test suite.

    Parameters
    ----------
      msg : string
        Optional message to be added.

    Returns
    -------
       decorator : function
         Decorator, which, when applied to a function, causes SkipTest
         to be raised, with the optional message added.
      """

    return skipif(True,msg)
qconf_api.py 文件源码 项目:config-api 作者: gridengine 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def api_call(*dargs, **dkwargs):
        def internal_call(func):
            @wraps(func)
            def wrapped_call(func, *args, **kwargs):
                try:
                    result = func(*args, **kwargs)
                    return result
                except QconfException, ex:
                    raise
                except Exception, ex:
                    raise QconfException(exception=ex)
            return decorator(wrapped_call, func)
        if len(dargs) == 1 and callable(dargs[0]):
            return internal_call(dargs[0])
        else:
            return internal_call
handler.py 文件源码 项目:twisted-json-rpc 作者: elston 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def method(name):
    def decorator(func):
        # ...
        _conspect_name(func, name)
        _conspect_param(func,func)
        # ...
        return func
    return decorator


# ...
# ...
# ...
utility.py 文件源码 项目:mugen 作者: scherroman 项目源码 文件源码 阅读 61 收藏 0 点赞 0 评论 0
def preprocess_args(fun: Callable, varnames: List[str]):
    """ 
    Applies fun to variables in varnames before launching the function 
    """
    def wrapper(f, *a, **kw):
        func_code = f.__code__

        names = func_code.co_varnames
        new_a = [fun(arg) if (name in varnames) else arg
                 for (arg, name) in zip(a, names)]
        new_kw = {k: fun(v) if k in varnames else v
                  for (k, v) in kw.items()}
        return f(*new_a, **new_kw)

    return decorator.decorator(wrapper)
jsonp.py 文件源码 项目:dati-ckan-docker 作者: italia 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def jsonpify(func, *args, **kwargs):
    """A decorator that reformats the output as JSON; or, if the
    *callback* parameter is specified (in the HTTP request), as JSONP.

    Very much modelled after pylons.decorators.jsonify .
    """
    data = func(*args, **kwargs)
    return to_jsonp(data)
test_merger_arxiv2arxiv.py 文件源码 项目:inspire-json-merger 作者: inspirehep 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def cover(key):
    # collect the schema's key verified by a test
    def tag(func):
        def wrapper(func, *args, **kwargs):
            COVERED_SCHEMA_KEYS.append(key)
            return func(*args, **kwargs)
        return decorator.decorator(wrapper, func)
    return tag
action.py 文件源码 项目:qiime2 作者: qiime2 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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 async 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)
            pool.shutdown(wait=False)
            return future

        async_wrapper = self._rewrite_wrapper_signature(async_wrapper)
        self._set_wrapper_properties(async_wrapper)
        self._set_wrapper_name(async_wrapper, 'async')
        return async_wrapper
action.py 文件源码 项目:qiime2 作者: qiime2 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
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))
magic.py 文件源码 项目:leetcode 作者: thomasyimgit 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def validate_type(magic_kind):
    """Ensure that the given magic_kind is valid.

    Check that the given magic_kind is one of the accepted spec types (stored
    in the global `magic_spec`), raise ValueError otherwise.
    """
    if magic_kind not in magic_spec:
        raise ValueError('magic_kind must be one of %s, %s given' %
                         magic_kinds, magic_kind)


# The docstrings for the decorator below will be fairly similar for the two
# types (method and function), so we generate them here once and reuse the
# templates below.


问题


面经


文章

微信
公众号

扫码关注公众号