Python inspect.iscoroutine() Examples

The following are 30 code examples of inspect.iscoroutine(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module inspect , or try the search function .
Example #1
Source File: testasync.py    From mock with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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) 
Example #2
Source File: test_inspect.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #3
Source File: test_inspect.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #4
Source File: test_aio.py    From prometheus-async with Apache License 2.0 6 votes vote down vote up
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 
Example #5
Source File: containers.py    From vibora with MIT License 6 votes vote down vote up
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) 
Example #6
Source File: coroutines.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #7
Source File: coroutines.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def iscoroutine(obj):
    """Return True if obj is a coroutine object."""
    return isinstance(obj, _COROUTINE_TYPES) 
Example #8
Source File: coro.py    From synapse with Apache License 2.0 5 votes vote down vote up
def iscoro(item):
    return inspect.iscoroutine(item) 
Example #9
Source File: testing.py    From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
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) 
Example #10
Source File: coroutines.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def iscoroutine(obj):
    """Return True if obj is a coroutine object."""
    if type(obj) in _iscoroutine_typecache:
        return True

    if isinstance(obj, _COROUTINE_TYPES):
        # Just in case we don't want to cache more than 100
        # positive types.  That shouldn't ever happen, unless
        # someone stressing the system on purpose.
        if len(_iscoroutine_typecache) < 100:
            _iscoroutine_typecache.add(type(obj))
        return True
    else:
        return False 
Example #11
Source File: coroutines.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def iscoroutinefunction(func):
    """Return True if func is a decorated coroutine function."""
    return (inspect.iscoroutinefunction(func) or
            getattr(func, '_is_coroutine', None) is _is_coroutine)


# Prioritize native coroutine check to speed-up
# asyncio.iscoroutine. 
Example #12
Source File: coroutines.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 = format_helpers.extract_stack(sys._getframe(1))
        self.__name__ = getattr(gen, '__name__', None)
        self.__qualname__ = getattr(gen, '__qualname__', None) 
Example #13
Source File: testing.py    From EventGhost with GNU General Public License v2.0 5 votes vote down vote up
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) 
Example #14
Source File: coroutines.py    From android_universal with MIT License 5 votes vote down vote up
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 = format_helpers.extract_stack(sys._getframe(1))
        self.__name__ = getattr(gen, '__name__', None)
        self.__qualname__ = getattr(gen, '__qualname__', None) 
Example #15
Source File: test_inspect.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
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)) 
Example #16
Source File: coroutines.py    From android_universal with MIT License 5 votes vote down vote up
def iscoroutinefunction(func):
    """Return True if func is a decorated coroutine function."""
    return (inspect.iscoroutinefunction(func) or
            getattr(func, '_is_coroutine', None) is _is_coroutine)


# Prioritize native coroutine check to speed-up
# asyncio.iscoroutine. 
Example #17
Source File: coroutines.py    From odoo13-x64 with GNU General Public License v3.0 5 votes vote down vote up
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 = format_helpers.extract_stack(sys._getframe(1))
        self.__name__ = getattr(gen, '__name__', None)
        self.__qualname__ = getattr(gen, '__qualname__', None) 
Example #18
Source File: task.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def __call__(self):
        """
        Run or resume a task.

        This attempts to execute a handler. If the handler is a coroutine it will attempt to
        await it. If there are done callbacks it will schedule them with the executor.

        The return value of the handler is stored as the task result.
        """
        if self._done or self._executing or not self._task_lock.acquire(blocking=False):
            return
        try:
            if self._done:
                return
            self._executing = True

            if inspect.iscoroutine(self._handler):
                # Execute a coroutine
                try:
                    self._handler.send(None)
                except StopIteration as e:
                    # The coroutine finished; store the result
                    self._handler.close()
                    self.set_result(e.value)
                    self._complete_task()
                except Exception as e:
                    self.set_exception(e)
                    self._complete_task()
            else:
                # Execute a normal function
                try:
                    self.set_result(self._handler(*self._args, **self._kwargs))
                except Exception as e:
                    self.set_exception(e)
                self._complete_task()

            self._executing = False
        finally:
            self._task_lock.release() 
Example #19
Source File: f_LiffService.py    From AsyncLine with MIT License 5 votes vote down vote up
def process(self, ctx, iprot, oprot):
        args = revokeToken_args()
        args.read(iprot)
        iprot.readMessageEnd()
        result = revokeToken_result()
        try:
            ret = self._handler([ctx, args.request])
            if inspect.iscoroutine(ret):
                ret = await ret
        except TApplicationException as ex:
            async with self._lock:
                _write_application_exception(ctx, oprot, "revokeToken", exception=ex)
                return
        except LiffException as e:
            result.e = e
        except Exception as e:
            async with self._lock:
                _write_application_exception(ctx, oprot, "revokeToken", ex_code=TApplicationExceptionType.INTERNAL_ERROR, message=str(e))
            raise
        async with self._lock:
            try:
                oprot.write_response_headers(ctx)
                oprot.writeMessageBegin('revokeToken', TMessageType.REPLY, 0)
                result.write(oprot)
                oprot.writeMessageEnd()
                oprot.get_transport().flush()
            except TTransportException as e:
                # catch a request too large error because the TMemoryOutputBuffer always throws that if too much data is written
                if e.type == TTransportExceptionType.REQUEST_TOO_LARGE:
                    raise _write_application_exception(ctx, oprot, "revokeToken", ex_code=TApplicationExceptionType.RESPONSE_TOO_LARGE, message=e.message)
                else:
                    raise e 
Example #20
Source File: f_LiffService.py    From AsyncLine with MIT License 5 votes vote down vote up
def process(self, ctx, iprot, oprot):
        args = issueLiffView_args()
        args.read(iprot)
        iprot.readMessageEnd()
        result = issueLiffView_result()
        try:
            ret = self._handler([ctx, args.request])
            if inspect.iscoroutine(ret):
                ret = await ret
            result.success = ret
        except TApplicationException as ex:
            async with self._lock:
                _write_application_exception(ctx, oprot, "issueLiffView", exception=ex)
                return
        except LiffException as e:
            result.e = e
        except Exception as e:
            async with self._lock:
                _write_application_exception(ctx, oprot, "issueLiffView", ex_code=TApplicationExceptionType.INTERNAL_ERROR, message=str(e))
            raise
        async with self._lock:
            try:
                oprot.write_response_headers(ctx)
                oprot.writeMessageBegin('issueLiffView', TMessageType.REPLY, 0)
                result.write(oprot)
                oprot.writeMessageEnd()
                oprot.get_transport().flush()
            except TTransportException as e:
                # catch a request too large error because the TMemoryOutputBuffer always throws that if too much data is written
                if e.type == TTransportExceptionType.REQUEST_TOO_LARGE:
                    raise _write_application_exception(ctx, oprot, "issueLiffView", ex_code=TApplicationExceptionType.RESPONSE_TOO_LARGE, message=e.message)
                else:
                    raise e 
Example #21
Source File: testasync.py    From mock with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_target_async_spec_not(self):
        @patch.object(AsyncClass, 'async_method', spec=NormalClass.a)
        def test_async_attribute(mock_method):
            self.assertIsInstance(mock_method, MagicMock)
            self.assertFalse(inspect.iscoroutine(mock_method))
            self.assertFalse(inspect.isawaitable(mock_method))

        test_async_attribute() 
Example #22
Source File: testasync.py    From mock with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_patch_with_autospec(self):

        async def test_async():
            with patch(f"{__name__}.async_func_args", autospec=True) as mock_method:
                awaitable = mock_method(1, 2, c=3)
                self.assertIsInstance(mock_method.mock, AsyncMock)

                self.assertTrue(iscoroutinefunction(mock_method))
                self.assertTrue(asyncio.iscoroutine(awaitable))
                self.assertTrue(inspect.isawaitable(awaitable))

                # Verify the default values during mock setup
                self.assertEqual(mock_method.await_count, 0)
                self.assertEqual(mock_method.await_args_list, [])
                self.assertIsNone(mock_method.await_args)
                mock_method.assert_not_awaited()

                await awaitable

            self.assertEqual(mock_method.await_count, 1)
            self.assertEqual(mock_method.await_args, call(1, 2, c=3))
            self.assertEqual(mock_method.await_args_list, [call(1, 2, c=3)])
            mock_method.assert_awaited_once()
            mock_method.assert_awaited_once_with(1, 2, c=3)
            mock_method.assert_awaited_with(1, 2, c=3)
            mock_method.assert_awaited()

            mock_method.reset_mock()
            self.assertEqual(mock_method.await_count, 0)
            self.assertIsNone(mock_method.await_args)
            self.assertEqual(mock_method.await_args_list, [])

        run(test_async()) 
Example #23
Source File: defer.py    From aiotools with MIT License 5 votes vote down vote up
def adefer(func):
    """
    An asynchronous version of the defer API.
    It can defer coroutine functions, coroutines, and normal functions.
    """
    assert inspect.iscoroutinefunction(func), \
           'the decorated function must be async'

    @functools.wraps(func)
    async def _wrapped(*args, **kwargs):
        deferreds = deque()

        def defer(f: Union[Callable, Awaitable]) -> None:
            deferreds.append(f)

        try:
            return await func(defer, *args, **kwargs)
        finally:
            while deferreds:
                f = deferreds.pop()
                if inspect.iscoroutinefunction(f):
                    await f()
                elif inspect.iscoroutine(f):
                    await f
                else:
                    f()

    return _wrapped 
Example #24
Source File: motor_asyncio.py    From umongo with MIT License 5 votes vote down vote up
def __coroutined_post_update(self, ret):
        ret = self.post_update(ret)
        if iscoroutine(ret):
            ret = await ret
        return ret 
Example #25
Source File: motor_asyncio.py    From umongo with MIT License 5 votes vote down vote up
def __coroutined_post_insert(self, ret):
        ret = self.post_insert(ret)
        if iscoroutine(ret):
            ret = await ret
        return ret 
Example #26
Source File: motor_asyncio.py    From umongo with MIT License 5 votes vote down vote up
def __coroutined_pre_delete(self):
        ret = self.pre_delete()
        if iscoroutine(ret):
            ret = await ret
        return ret 
Example #27
Source File: motor_asyncio.py    From umongo with MIT License 5 votes vote down vote up
def __coroutined_pre_update(self):
        ret = self.pre_update()
        if iscoroutine(ret):
            ret = await ret
        return ret 
Example #28
Source File: motor_asyncio.py    From umongo with MIT License 5 votes vote down vote up
def __coroutined_pre_insert(self):
        ret = self.pre_insert()
        if iscoroutine(ret):
            ret = await ret
        return ret 
Example #29
Source File: compat.py    From promise with MIT License 5 votes vote down vote up
def iscoroutine(obj):  # type: ignore
        return False 
Example #30
Source File: coroutines.py    From android_universal with MIT License 5 votes vote down vote up
def iscoroutine(obj):
    """Return True if obj is a coroutine object."""
    if type(obj) in _iscoroutine_typecache:
        return True

    if isinstance(obj, _COROUTINE_TYPES):
        # Just in case we don't want to cache more than 100
        # positive types.  That shouldn't ever happen, unless
        # someone stressing the system on purpose.
        if len(_iscoroutine_typecache) < 100:
            _iscoroutine_typecache.add(type(obj))
        return True
    else:
        return False