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


Python inspect.iscoroutine方法代码示例

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


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

示例1: test_decorator

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import iscoroutine [as 别名]
def test_decorator(self, fo, patch_timer):
        """
        time works with asyncio results functions.
        """

        @aio.time(fo)
        async def func():
            await asyncio.sleep(0)
            return 42

        rv = func()

        assert asyncio.iscoroutine(rv)
        assert [] == fo._observed

        rv = await rv

        assert [1] == fo._observed
        assert 42 == rv 
开发者ID:hynek,项目名称:prometheus-async,代码行数:21,代码来源:test_aio.py

示例2: test_iscoroutine

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import iscoroutine [as 别名]
def test_iscoroutine(self):
        gen_coro = gen_coroutine_function_example(1)
        coro = coroutine_function_example(1)

        self.assertFalse(
            inspect.iscoroutinefunction(gen_coroutine_function_example))
        self.assertFalse(inspect.iscoroutine(gen_coro))

        self.assertTrue(
            inspect.isgeneratorfunction(gen_coroutine_function_example))
        self.assertTrue(inspect.isgenerator(gen_coro))

        self.assertTrue(
            inspect.iscoroutinefunction(coroutine_function_example))
        self.assertTrue(inspect.iscoroutine(coro))

        self.assertFalse(
            inspect.isgeneratorfunction(coroutine_function_example))
        self.assertFalse(inspect.isgenerator(coro))

        coro.close(); gen_coro.close() # silence warnings 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:23,代码来源:test_inspect.py

示例3: test_create_autospec

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import iscoroutine [as 别名]
def test_create_autospec(self):
        spec = create_autospec(async_func_args)
        awaitable = spec(1, 2, c=3)
        async def main():
            await awaitable

        self.assertEqual(spec.await_count, 0)
        self.assertIsNone(spec.await_args)
        self.assertEqual(spec.await_args_list, [])
        spec.assert_not_awaited()

        run(main())

        self.assertTrue(iscoroutinefunction(spec))
        self.assertTrue(asyncio.iscoroutine(awaitable))
        self.assertEqual(spec.await_count, 1)
        self.assertEqual(spec.await_args, call(1, 2, c=3))
        self.assertEqual(spec.await_args_list, [call(1, 2, c=3)])
        spec.assert_awaited_once()
        spec.assert_awaited_once_with(1, 2, c=3)
        spec.assert_awaited_with(1, 2, c=3)
        spec.assert_awaited()

        with self.assertRaises(AssertionError):
            spec.assert_any_await(e=1) 
开发者ID:testing-cabal,项目名称:mock,代码行数:27,代码来源:testasync.py

示例4: __init__

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import iscoroutine [as 别名]
def __init__(self, name: str=None, path: str=None, content: bytes=None, iterable=None,
                 f=None, headers: list=None):
        if not any([path, content, iterable, f]):
            raise Exception('You must supply either: path, content, iterable, f')
        self.name = name
        if f:
            self.f = f
        elif path:
            self.f = open(path, 'rb')
            if not self.name:
                self.name = os.path.basename(path)
        elif content:
            self.f = BytesIO(initial_bytes=content)
        elif iterable:
            self.f = BufferedIterable(iterable)
        if not self.name:
            self.name = str(uuid.uuid4())
        self.headers = headers
        self.is_async = inspect.iscoroutine(self.f.read) 
开发者ID:vibora-io,项目名称:vibora,代码行数:21,代码来源:containers.py

示例5: __function

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import iscoroutine [as 别名]
def __function(self, func, *args, **kwargs):
        args = list(args)
        kwargs = dict(kwargs)
        for i, arg in enumerate(args):
            if isinstance(arg, type(self)):
                args[i] = arg.__under
        for key, arg in kwargs.items():
            if isinstance(arg, type(self)):
                kwargs[key] = arg.__under
        kwargs.setdefault("parse_mode", "markdown")
        try:
            ret = func(*args, **kwargs)
        except TypeError:
            del kwargs["parse_mode"]
            ret = func(*args, **kwargs)
        else:
            if inspect.iscoroutine(ret):
                async def wrapper():
                    try:
                        ret2 = await ret
                    except TypeError:
                        del kwargs["parse_mode"]
                        ret2 = await func(*args, **kwargs)
                    return self.__convert(ret2)
                return wrapper()
        return self.__convert(ret) 
开发者ID:friendly-telegram,项目名称:friendly-telegram,代码行数:28,代码来源:util.py

示例6: __convert

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import iscoroutine [as 别名]
def __convert(self, ret):
        if inspect.iscoroutine(ret):
            async def wrapper():
                return self.__convert(await ret)
            return wrapper()
        if isinstance(ret, list):
            for i, thing in enumerate(ret):
                ret[i] = self.__convert(thing)
        elif getattr(getattr(getattr(ret, "__self__", ret),
                             "__class__", None), "__module__", "").startswith("telethon"):
            ret = MarkdownBotPassthrough(ret)
            if hasattr(ret, "text"):
                logger.debug("%r(%s) %r(%s)", ret.entities, type(ret.entities), ret.message, type(ret.message))
                ret.text = markdown.unparse(ret.message, [x.__under for x in ret.entities or []])
        return ret 
开发者ID:friendly-telegram,项目名称:friendly-telegram,代码行数:17,代码来源:util.py

示例7: callback

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import iscoroutine [as 别名]
def callback(func):
    """
    This decorator turns `func` into a callback for Tkinter
    to be able to use, even if `func` is an awaitable coroutine.
    """
    @functools.wraps(func)
    def wrapped(*args, **kwargs):
        result = func(*args, **kwargs)
        if inspect.iscoroutine(result):
            aio_loop.create_task(result)

    return wrapped 
开发者ID:LonamiWebs,项目名称:Telethon,代码行数:14,代码来源:gui.py

示例8: __call__

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import iscoroutine [as 别名]
def __call__(self, *args, **kwargs):
        result = self.orig_method(*args, **kwargs)
        if isinstance(result, GeneratorType) or iscoroutine(result):
            raise TypeError("Generator and coroutine test methods should be"
                            " decorated with tornado.testing.gen_test")
        elif result is not None:
            raise ValueError("Return value from test method ignored: %r" %
                             result) 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:10,代码来源:testing.py

示例9: _scheduled_task

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import iscoroutine [as 别名]
def _scheduled_task(self, data: TaskData) -> None:
        """Await the `data.callback` coroutine after waiting for `data.wait_time` seconds."""
        try:
            log.trace(f"Waiting {data.wait_time} seconds before awaiting callback.")
            await asyncio.sleep(data.wait_time)

            # Use asyncio.shield to prevent callback from cancelling itself.
            # The parent task (_scheduled_task) will still get cancelled.
            log.trace("Done waiting; now awaiting the callback.")
            await asyncio.shield(data.callback)
        finally:
            if inspect.iscoroutine(data.callback):
                log.trace("Explicitly closing coroutine.")
                data.callback.close() 
开发者ID:python-discord,项目名称:bot,代码行数:16,代码来源:help_channels.py

示例10: _is_coroutine

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import iscoroutine [as 别名]
def _is_coroutine(obj):

    return inspect.iscoroutine(obj) or isinstance(obj, asyncio.coroutines.CoroWrapper)


##
## Exceptions
## 
开发者ID:facebookincubator,项目名称:TestSlide,代码行数:10,代码来源:mock_callable.py

示例11: __call__

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import iscoroutine [as 别名]
def __call__(self, *args: Any, **kwargs: Any) -> None:
        result = self.orig_method(*args, **kwargs)
        if isinstance(result, Generator) or inspect.iscoroutine(result):
            raise TypeError(
                "Generator and coroutine test methods should be"
                " decorated with tornado.testing.gen_test"
            )
        elif result is not None:
            raise ValueError("Return value from test method ignored: %r" % result) 
开发者ID:opendevops-cn,项目名称:opendevops,代码行数:11,代码来源:testing.py

示例12: test_still_coroutine_function

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import iscoroutine [as 别名]
def test_still_coroutine_function(self, fo):
        """
        It's ensured that a decorated function still passes as a coroutine
        function.  Otherwise PYTHONASYNCIODEBUG=1 breaks.
        """
        func = aio.time(fo)(coro)
        new_coro = func()

        assert inspect.iscoroutine(new_coro)
        assert inspect.iscoroutinefunction(func)

        await new_coro 
开发者ID:hynek,项目名称:prometheus-async,代码行数:14,代码来源:test_aio.py

示例13: __init__

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import iscoroutine [as 别名]
def __init__(self, gen, func=None):
        assert inspect.isgenerator(gen) or inspect.iscoroutine(gen), gen
        self.gen = gen
        self.func = func # Used to unwrap @coroutine decorator
        self._source_traceback = traceback.extract_stack(sys._getframe(1))
        self.__name__ = getattr(gen, '__name__', None)
        self.__qualname__ = getattr(gen, '__qualname__', None) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:9,代码来源:coroutines.py

示例14: iscoroutine

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import iscoroutine [as 别名]
def iscoroutine(obj):
    """Return True if obj is a coroutine object."""
    return isinstance(obj, _COROUTINE_TYPES) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:5,代码来源:coroutines.py

示例15: test_excluding_predicates

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import iscoroutine [as 别名]
def test_excluding_predicates(self):
        global tb
        self.istest(inspect.isbuiltin, 'sys.exit')
        self.istest(inspect.isbuiltin, '[].append')
        self.istest(inspect.iscode, 'mod.spam.__code__')
        try:
            1/0
        except:
            tb = sys.exc_info()[2]
            self.istest(inspect.isframe, 'tb.tb_frame')
            self.istest(inspect.istraceback, 'tb')
            if hasattr(types, 'GetSetDescriptorType'):
                self.istest(inspect.isgetsetdescriptor,
                            'type(tb.tb_frame).f_locals')
            else:
                self.assertFalse(inspect.isgetsetdescriptor(type(tb.tb_frame).f_locals))
        finally:
            # Clear traceback and all the frames and local variables hanging to it.
            tb = None
        self.istest(inspect.isfunction, 'mod.spam')
        self.istest(inspect.isfunction, 'mod.StupidGit.abuse')
        self.istest(inspect.ismethod, 'git.argue')
        self.istest(inspect.ismodule, 'mod')
        self.istest(inspect.isdatadescriptor, 'collections.defaultdict.default_factory')
        self.istest(inspect.isgenerator, '(x for x in range(2))')
        self.istest(inspect.isgeneratorfunction, 'generator_function_example')

        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            self.istest(inspect.iscoroutine, 'coroutine_function_example(1)')
            self.istest(inspect.iscoroutinefunction, 'coroutine_function_example')

        if hasattr(types, 'MemberDescriptorType'):
            self.istest(inspect.ismemberdescriptor, 'datetime.timedelta.days')
        else:
            self.assertFalse(inspect.ismemberdescriptor(datetime.timedelta.days)) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:38,代码来源:test_inspect.py


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