當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。