當前位置: 首頁>>代碼示例>>Python>>正文


Python inspect.unwrap方法代碼示例

本文整理匯總了Python中inspect.unwrap方法的典型用法代碼示例。如果您正苦於以下問題:Python inspect.unwrap方法的具體用法?Python inspect.unwrap怎麽用?Python inspect.unwrap使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在inspect的用法示例。


在下文中一共展示了inspect.unwrap方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: unwrap

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import unwrap [as 別名]
def unwrap(func, *, stop=None):
        """This is the inspect.unwrap() method copied from Python 3.5's standard library."""
        if stop is None:
            def _is_wrapper(f):
                return hasattr(f, '__wrapped__')
        else:
            def _is_wrapper(f):
                return hasattr(f, '__wrapped__') and not stop(f)
        f = func  # remember the original func for error reporting
        memo = {id(f)}  # Memoise by id to tolerate non-hashable objects
        while _is_wrapper(func):
            func = func.__wrapped__
            id_func = id(func)
            if id_func in memo:
                raise ValueError('wrapper loop when unwrapping {!r}'.format(f))
            memo.add(id_func)
        return func 
開發者ID:instaloader,項目名稱:instaloader,代碼行數:19,代碼來源:sphinx_autodoc_typehints.py

示例2: unwrap

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import unwrap [as 別名]
def unwrap(func, stop=None):
        # NOTE: implementation is taken from CPython/Lib/inspect.py, Python 3.6
        if stop is None:

            def _is_wrapper(f):
                return hasattr(f, "__wrapped__")

        else:

            def _is_wrapper(f):
                return hasattr(f, "__wrapped__") and not stop(f)

        f = func  # remember the original func for error reporting
        memo = {id(f)}  # Memoise by id to tolerate non-hashable objects
        while _is_wrapper(func):
            func = func.__wrapped__
            id_func = id(func)
            if id_func in memo:
                raise ValueError("wrapper loop when unwrapping {!r}".format(f))
            memo.add(id_func)
        return func 
開發者ID:ssanderson,項目名稱:python-interface,代碼行數:23,代碼來源:compat.py

示例3: args_check

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import unwrap [as 別名]
def args_check(name, func, provided):
        provided = list(provided)
        # First argument, filter input, is implied.
        plen = len(provided) + 1
        # Check to see if a decorator is providing the real function.
        func = unwrap(func)

        args, _, _, defaults, _, _, _ = getfullargspec(func)
        alen = len(args)
        dlen = len(defaults or [])
        # Not enough OR Too many
        if plen < (alen - dlen) or plen > alen:
            raise TemplateSyntaxError("%s requires %d arguments, %d provided" %
                                      (name, alen - dlen, plen))

        return True 
開發者ID:PacktPublishing,項目名稱:Hands-On-Application-Development-with-PyCharm,代碼行數:18,代碼來源:base.py

示例4: _get_function_source

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import unwrap [as 別名]
def _get_function_source(func):
    if _PY34:
        func = inspect.unwrap(func)
    elif hasattr(func, '__wrapped__'):
        func = func.__wrapped__

    if inspect.isfunction(func):
        code = func.__code__
        return (code.co_filename, code.co_firstlineno)

    if isinstance(func, functools.partial):
        return _get_function_source(func.func)

    if _PY34 and isinstance(func, functools.partialmethod):
        return _get_function_source(func.func)
    return None 
開發者ID:hhstore,項目名稱:annotated-py-projects,代碼行數:18,代碼來源:events.py

示例5: _get_position_of_obj

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import unwrap [as 別名]
def _get_position_of_obj(self, obj, quiet=False):
        if hasattr(inspect, "unwrap"):
            obj = inspect.unwrap(obj)
        if isinstance(obj, str):
            return obj, 1, None
        try:
            filename = inspect.getabsfile(obj)
            lines, lineno = inspect.getsourcelines(obj)
        except (IOError, TypeError) as e:
            if not quiet:
                print('** Error: %s **' % e, file=self.stdout)
            return None, None, None
        return filename, lineno, lines 
開發者ID:pdbpp,項目名稱:pdbpp,代碼行數:15,代碼來源:pdbpp.py

示例6: _patch_unwrap_mock_aware

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import unwrap [as 別名]
def _patch_unwrap_mock_aware():
    """
    contextmanager which replaces ``inspect.unwrap`` with a version
    that's aware of mock objects and doesn't recurse on them
    """
    real_unwrap = inspect.unwrap

    def _mock_aware_unwrap(obj, stop=None):
        try:
            if stop is None or stop is _is_mocked:
                return real_unwrap(obj, stop=_is_mocked)
            return real_unwrap(obj, stop=lambda obj: _is_mocked(obj) or stop(obj))
        except Exception as e:
            warnings.warn(
                "Got %r when unwrapping %r.  This is usually caused "
                "by a violation of Python's object protocol; see e.g. "
                "https://github.com/pytest-dev/pytest/issues/5080" % (e, obj),
                PytestWarning,
            )
            raise

    inspect.unwrap = _mock_aware_unwrap
    try:
        yield
    finally:
        inspect.unwrap = real_unwrap 
開發者ID:sofia-netsurv,項目名稱:python-netsurv,代碼行數:28,代碼來源:doctest.py

示例7: _patch_unwrap_mock_aware

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import unwrap [as 別名]
def _patch_unwrap_mock_aware() -> Generator[None, None, None]:
    """
    contextmanager which replaces ``inspect.unwrap`` with a version
    that's aware of mock objects and doesn't recurse on them
    """
    real_unwrap = inspect.unwrap

    def _mock_aware_unwrap(
        func: Callable[..., Any], *, stop: Optional[Callable[[Any], Any]] = None
    ) -> Any:
        try:
            if stop is None or stop is _is_mocked:
                return real_unwrap(func, stop=_is_mocked)
            _stop = stop
            return real_unwrap(func, stop=lambda obj: _is_mocked(obj) or _stop(func))
        except Exception as e:
            warnings.warn(
                "Got %r when unwrapping %r.  This is usually caused "
                "by a violation of Python's object protocol; see e.g. "
                "https://github.com/pytest-dev/pytest/issues/5080" % (e, func),
                PytestWarning,
            )
            raise

    inspect.unwrap = _mock_aware_unwrap
    try:
        yield
    finally:
        inspect.unwrap = real_unwrap 
開發者ID:pytest-dev,項目名稱:pytest,代碼行數:31,代碼來源:doctest.py

示例8: test_warning_on_unwrap_of_broken_object

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import unwrap [as 別名]
def test_warning_on_unwrap_of_broken_object(
    stop: Optional[Callable[[object], object]]
) -> None:
    bad_instance = Broken()
    assert inspect.unwrap.__module__ == "inspect"
    with _patch_unwrap_mock_aware():
        assert inspect.unwrap.__module__ != "inspect"
        with pytest.warns(
            pytest.PytestWarning, match="^Got KeyError.* when unwrapping"
        ):
            with pytest.raises(KeyError):
                inspect.unwrap(bad_instance, stop=stop)  # type: ignore[arg-type] # noqa: F821
    assert inspect.unwrap.__module__ == "inspect" 
開發者ID:pytest-dev,項目名稱:pytest,代碼行數:15,代碼來源:test_doctest.py

示例9: _get_function_source

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import unwrap [as 別名]
def _get_function_source(func):
    if compat.PY34:
        func = inspect.unwrap(func)
    elif hasattr(func, '__wrapped__'):
        func = func.__wrapped__
    if inspect.isfunction(func):
        code = func.__code__
        return (code.co_filename, code.co_firstlineno)
    if isinstance(func, functools.partial):
        return _get_function_source(func.func)
    if compat.PY34 and isinstance(func, functools.partialmethod):
        return _get_function_source(func.func)
    return None 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:15,代碼來源:events.py

示例10: test_unwrap_one

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import unwrap [as 別名]
def test_unwrap_one(self):
        def func(a, b):
            return a + b
        wrapper = functools.lru_cache(maxsize=20)(func)
        self.assertIs(inspect.unwrap(wrapper), func) 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:7,代碼來源:test_inspect.py

示例11: test_unwrap_several

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import unwrap [as 別名]
def test_unwrap_several(self):
        def func(a, b):
            return a + b
        wrapper = func
        for __ in range(10):
            @functools.wraps(wrapper)
            def wrapper():
                pass
        self.assertIsNot(wrapper.__wrapped__, func)
        self.assertIs(inspect.unwrap(wrapper), func) 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:12,代碼來源:test_inspect.py

示例12: test_stop

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import unwrap [as 別名]
def test_stop(self):
        def func1(a, b):
            return a + b
        @functools.wraps(func1)
        def func2():
            pass
        @functools.wraps(func2)
        def wrapper():
            pass
        func2.stop_here = 1
        unwrapped = inspect.unwrap(wrapper,
                                   stop=(lambda f: hasattr(f, "stop_here")))
        self.assertIs(unwrapped, func2) 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:15,代碼來源:test_inspect.py

示例13: test_cycle

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import unwrap [as 別名]
def test_cycle(self):
        def func1(): pass
        func1.__wrapped__ = func1
        with self.assertRaisesRegex(ValueError, 'wrapper loop'):
            inspect.unwrap(func1)

        def func2(): pass
        func2.__wrapped__ = func1
        func1.__wrapped__ = func2
        with self.assertRaisesRegex(ValueError, 'wrapper loop'):
            inspect.unwrap(func1)
        with self.assertRaisesRegex(ValueError, 'wrapper loop'):
            inspect.unwrap(func2) 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:15,代碼來源:test_inspect.py

示例14: unwrap_py2

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import unwrap [as 別名]
def unwrap_py2(func):
    """Unwrap a wrapped function.
    The function inspect.unwrap has been implemented only in Python 3.4. With
    Python 2, this works only for functions wrapped by wraps_py2().
    """
    unwrapped_func = func
    try:
        while True:
            unwrapped_func = unwrapped_func.__wrapped__
    except AttributeError:
        return unwrapped_func 
開發者ID:choderalab,項目名稱:openmmtools,代碼行數:13,代碼來源:testsystems.py

示例15: _get_function_source

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import unwrap [as 別名]
def _get_function_source(func):
    func = inspect.unwrap(func)
    if inspect.isfunction(func):
        code = func.__code__
        return (code.co_filename, code.co_firstlineno)
    if isinstance(func, functools.partial):
        return _get_function_source(func.func)
    if isinstance(func, functools.partialmethod):
        return _get_function_source(func.func)
    return None 
開發者ID:CedricGuillemet,項目名稱:Imogen,代碼行數:12,代碼來源:format_helpers.py


注:本文中的inspect.unwrap方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。