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