当前位置: 首页>>代码示例>>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;未经允许,请勿转载。