当前位置: 首页>>代码示例>>Python>>正文


Python decorator.decorate方法代码示例

本文整理汇总了Python中decorator.decorate方法的典型用法代码示例。如果您正苦于以下问题:Python decorator.decorate方法的具体用法?Python decorator.decorate怎么用?Python decorator.decorate使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在decorator的用法示例。


在下文中一共展示了decorator.decorate方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: logging_scope

# 需要导入模块: import decorator [as 别名]
# 或者: from decorator import decorate [as 别名]
def logging_scope(name, *wargs, **wkwargs):
    """
    A decorator to add the decorated function as a new logging scope, with name `name`.
    All additional arguments are passed to `StatusLogger._scope_enter`. Current
    supported keyword arguments are "timed", in which case when the scope closes,
    the duration of the call is shown.
    """
    def logging_scope(func, *args, **kwargs):
        logger._scope_enter(name, *wargs, **wkwargs)
        success = True
        try:
            f = func(*args, **kwargs)
            return f
        except Exception as e:
            success = False
            raise_with_traceback(e)
        finally:
            logger._scope_exit(success)
    return lambda func: decorate(func, logging_scope) 
开发者ID:airbnb,项目名称:omniduct,代码行数:21,代码来源:debug.py

示例2: _helpCls

# 需要导入模块: import decorator [as 别名]
# 或者: from decorator import decorate [as 别名]
def _helpCls(receiverCls, helperCls):
    iscallable = lambda f: hasattr(f, "__call__")
    for name, oldMethod in inspect.getmembers(helperCls, predicate=iscallable):
        # We will use decorator.decorate to ensure that attributes of oldMethod, like
        # docstring and signature, are inherited by newMethod. decorator.decorate
        # won't accept an unbound method, so for Python 2 we extract oldMethod's
        # implementing function __func__. In Python 3, inspect.getmembers will return
        # the implementing functions insead of unbound method - this is due to
        # Python 3's data model.
        try:
            impl = oldMethod.__func__
        except:
            impl = oldMethod
        if not name.startswith("_"):
            newMethod = _getUnboundMethod(helperCls, impl)
            setattr(receiverCls, name, newMethod) 
开发者ID:TresAmigosSD,项目名称:SMV,代码行数:18,代码来源:helpers.py

示例3: count_calls

# 需要导入模块: import decorator [as 别名]
# 或者: from decorator import decorate [as 别名]
def count_calls(counter):
    """
    A decorator which counts the number of times the decorated function is
    called using the counter argument.
    """

    def call_counts_inner(func):
        def wrapper(func, *args, **kwargs):
            counter.mark()
            return func(*args, **kwargs)

        wrapped = decorate(func, wrapper)
        counter.reset()
        return wrapped

    return call_counts_inner 
开发者ID:square,项目名称:bionic,代码行数:18,代码来源:helpers.py

示例4: decorate

# 需要导入模块: import decorator [as 别名]
# 或者: from decorator import decorate [as 别名]
def decorate(func, fwrapped):
    """A wrapper call of decorator package, differs to call time

    Parameters
    ----------
    func : function
        The original function

    fwrapped : function
        The wrapped function
    """
    import decorator
    return decorator.decorate(func, fwrapped)


#-----------------------------------------
# Base code for structured error handling.
#-----------------------------------------
# Maps error type to its constructor 
开发者ID:apache,项目名称:incubator-tvm,代码行数:21,代码来源:base.py

示例5: decorate

# 需要导入模块: import decorator [as 别名]
# 或者: from decorator import decorate [as 别名]
def decorate(func, fwrapped):
    """A wrapper call of decorator package, differs to call time

    Parameters
    ----------
    func : function
        The original function

    fwrapped : function
        The wrapped function
    """
    import decorator
    return decorator.decorate(func, fwrapped) 
开发者ID:dmlc,项目名称:dgl,代码行数:15,代码来源:base.py

示例6: _getUnboundMethod

# 需要导入模块: import decorator [as 别名]
# 或者: from decorator import decorate [as 别名]
def _getUnboundMethod(helperCls, oldMethod):
    def newMethod(_oldMethod, self, *args, **kwargs):
        return _oldMethod(helperCls(self), *args, **kwargs)

    return decorator.decorate(oldMethod, newMethod) 
开发者ID:TresAmigosSD,项目名称:SMV,代码行数:7,代码来源:helpers.py

示例7: api_version

# 需要导入模块: import decorator [as 别名]
# 或者: from decorator import decorate [as 别名]
def api_version(created_ver, last_changed_ver, return_value_ver):
    """Version check decorator. Currently only checks Bigger Than."""
    def api_min_version_decorator(function):      
        def wrapper(function, self, *args, **kwargs):
            if not self.version_check_mode == "none":
                if self.version_check_mode == "created":
                    version = created_ver
                else:
                    version = bigger_version(last_changed_ver, return_value_ver)
                major, minor, patch = parse_version_string(version)
                if major > self.mastodon_major:
                    raise MastodonVersionError("Version check failed (Need version " + version + ")")
                elif major == self.mastodon_major and minor > self.mastodon_minor:
                    print(self.mastodon_minor)
                    raise MastodonVersionError("Version check failed (Need version " + version + ")")
                elif major == self.mastodon_major and minor == self.mastodon_minor and patch > self.mastodon_patch:
                    raise MastodonVersionError("Version check failed (Need version " + version + ", patch is " + str(self.mastodon_patch) + ")")
            return function(self, *args, **kwargs)
        function.__doc__ = function.__doc__ + "\n\n        *Added: Mastodon v" + created_ver + ", last changed: Mastodon v" + last_changed_ver + "*"
        return decorate(function, wrapper)
    return api_min_version_decorator

###
# Dict helper class.
# Defined at top level so it can be pickled.
### 
开发者ID:halcy,项目名称:Mastodon.py,代码行数:28,代码来源:Mastodon.py

示例8: session_check

# 需要导入模块: import decorator [as 别名]
# 或者: from decorator import decorate [as 别名]
def session_check(f):
    return decorate(f, _session_check)

# reconnect methods currenlty focus on Samurai only
# need to enhance this 
开发者ID:bachng2017,项目名称:RENAT,代码行数:7,代码来源:WebApp.py

示例9: with_reconnect

# 需要导入模块: import decorator [as 别名]
# 或者: from decorator import decorate [as 别名]
def with_reconnect(f):
    return decorate(f, _with_reconnect)


### 
开发者ID:bachng2017,项目名称:RENAT,代码行数:7,代码来源:WebApp.py

示例10: trace

# 需要导入模块: import decorator [as 别名]
# 或者: from decorator import decorate [as 别名]
def trace(f):
    return decorate(f, _trace) 
开发者ID:chishui,项目名称:terminal-leetcode,代码行数:4,代码来源:trace.py

示例11: memoize

# 需要导入模块: import decorator [as 别名]
# 或者: from decorator import decorate [as 别名]
def memoize(key):
    """Memoize the result of function and reuse multiple times.

    Parameters
    ----------
    key: str
        The unique key to the file

    Returns
    -------
    fmemoize : function
        The decorator function to perform memoization.
    """
    def _register(f):
        """Registration function"""
        allow_types = (string_types, int, float)
        fkey = key + "." + f.__name__ + ".pkl"
        if fkey not in Cache.cache_by_key:
            Cache.cache_by_key[fkey] = Cache(fkey)
        cache = Cache.cache_by_key[fkey]
        cargs = tuple(x.cell_contents for x in f.__closure__)
        cargs = (len(cargs),) + cargs

        def _memoized_f(func, *args, **kwargs):
            assert not kwargs, "Only allow positional call"
            key = cargs + args
            for arg in key:
                if isinstance(arg, tuple):
                    for x in arg:
                        assert isinstance(x, allow_types)
                else:
                    assert isinstance(arg, allow_types)
            if key in cache.cache:
                return cache.cache[key]
            res = func(*args)
            cache.cache[key] = res
            cache.dirty = True
            return res

        return decorate(f, _memoized_f)

    return _register 
开发者ID:mlperf,项目名称:training_results_v0.6,代码行数:44,代码来源:pickle_memoize.py

示例12: memoize

# 需要导入模块: import decorator [as 别名]
# 或者: from decorator import decorate [as 别名]
def memoize(key, save_at_exit=False):
    """Memoize the result of function and reuse multiple times.

    Parameters
    ----------
    key: str
        The unique key to the file
    save_at_exit: bool
        Whether save the cache to file when the program exits

    Returns
    -------
    fmemoize : function
        The decorator function to perform memoization.
    """
    def _register(f):
        """Registration function"""
        allow_types = (string_types, int, float, tuple)
        fkey = key + "." + f.__name__ + ".pkl"
        if fkey not in Cache.cache_by_key:
            Cache.cache_by_key[fkey] = Cache(fkey, save_at_exit)
        cache = Cache.cache_by_key[fkey]
        cargs = tuple(x.cell_contents for x in f.__closure__) if f.__closure__ else ()
        cargs = (len(cargs),) + cargs

        def _memoized_f(func, *args, **kwargs):
            assert not kwargs, "Only allow positional call"
            key = cargs + args
            for arg in key:
                if isinstance(arg, tuple):
                    for x in arg:
                        assert isinstance(x, allow_types)
                else:
                    assert isinstance(arg, allow_types)
            if key in cache.cache:
                return cache.cache[key]
            res = func(*args)
            cache.cache[key] = res
            cache.dirty = True
            return res

        return decorate(f, _memoized_f)

    return _register 
开发者ID:apache,项目名称:incubator-tvm,代码行数:46,代码来源:pickle_memoize.py


注:本文中的decorator.decorate方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。