Python inspect.isawaitable() Examples

The following are 30 code examples of inspect.isawaitable(). 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: item.py    From ruia with Apache License 2.0 6 votes vote down vote up
def _parse_html(cls, *, html_etree: etree._Element):
        if html_etree is None:
            raise ValueError("<Item: html_etree is expected>")
        item_ins = cls()
        fields_dict = getattr(item_ins, "__fields", {})
        for field_name, field_value in fields_dict.items():
            if not field_name.startswith("target_"):
                clean_method = getattr(item_ins, f"clean_{field_name}", None)
                value = field_value.extract(html_etree)
                if clean_method is not None and callable(clean_method):
                    try:
                        aws_clean_func = clean_method(value)
                        if isawaitable(aws_clean_func):
                            value = await aws_clean_func
                        else:
                            raise InvalidFuncType(
                                f"<Item: clean_method must be a coroutine function>"
                            )
                    except IgnoreThisItem:
                        item_ins.ignore_item = True

                setattr(item_ins, field_name, value)
                item_ins.results[field_name] = value
        return item_ins 
Example #2
Source File: tasks.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def ensure_future(coro_or_future, *, loop=None):
    """Wrap a coroutine or an awaitable in a future.

    If the argument is a Future, it is returned directly.
    """
    if isinstance(coro_or_future, futures.Future):
        if loop is not None and loop is not coro_or_future._loop:
            raise ValueError('loop argument must agree with Future')
        return coro_or_future
    elif coroutines.iscoroutine(coro_or_future):
        if loop is None:
            loop = events.get_event_loop()
        task = loop.create_task(coro_or_future)
        if task._source_traceback:
            del task._source_traceback[-1]
        return task
    elif compat.PY35 and inspect.isawaitable(coro_or_future):
        return ensure_future(_wrap_awaitable(coro_or_future), loop=loop)
    else:
        raise TypeError('A Future, a coroutine or an awaitable is required') 
Example #3
Source File: app.py    From sanic with MIT License 6 votes vote down vote up
def _run_response_middleware(
        self, request, response, request_name=None
    ):
        named_middleware = self.named_response_middleware.get(
            request_name, deque()
        )
        applicable_middleware = self.response_middleware + named_middleware
        if applicable_middleware:
            for middleware in applicable_middleware:
                _response = middleware(request, response)
                if isawaitable(_response):
                    _response = await _response
                if _response:
                    response = _response
                    break
        return response 
Example #4
Source File: engine.py    From tartiflette with MIT License 6 votes vote down vote up
def _bake_module(
    module: object, schema_name: str, config: Optional[Dict[str, Any]] = None
) -> str:
    """
    Bakes a module and retrieves its extra SDL content.
    :param module: module instance to bake
    :param schema_name: schema name to link with
    :param config: configuration of the module
    :type module: object
    :type schema_name: str
    :type config: Optional[Dict[str, Any]]
    :return: the extra SDL provided by the module
    :rtype: str
    """
    msdl = module.bake(schema_name, config)
    if isawaitable(msdl):
        msdl = await msdl
    return msdl or "" 
Example #5
Source File: asgi.py    From sanic with MIT License 6 votes vote down vote up
def shutdown(self) -> None:
        """
        Gather the listeners to fire on server stop.
        Because we are using a third-party server and not Sanic server, we do
        not have access to fire anything AFTER the server stops.
        Therefore, we fire before_server_stop and after_server_stop
        in sequence since the ASGI lifespan protocol only supports a single
        shutdown event.
        """
        listeners = self.asgi_app.sanic_app.listeners.get(
            "before_server_stop", []
        ) + self.asgi_app.sanic_app.listeners.get("after_server_stop", [])

        for handler in listeners:
            response = handler(
                self.asgi_app.sanic_app, self.asgi_app.sanic_app.loop
            )
            if isawaitable(response):
                await response 
Example #6
Source File: async_utils.py    From gd.py with MIT License 6 votes vote down vote up
def gather(
    *aws: Sequence[Awaitable],
    loop: Optional[asyncio.AbstractEventLoop] = None,
    return_exceptions: bool = False,
) -> List[Any]:
    """A function that is calling :func:`asyncio.gather`.

    Used for less imports inside and outside gd.py.

    One small addition is that a sequence of awaitables can be given
    as the only positional argument.

    This way, :func:`asyncio.gather` will be run on that sequence.
    """
    if len(aws) == 1:
        maybe_aw = aws[0]
        if not inspect.isawaitable(maybe_aw):
            aws = maybe_aw

    return await asyncio.gather(*aws, loop=loop, return_exceptions=return_exceptions) 
Example #7
Source File: resourcestatistics.py    From apex-sigma-core with GNU General Public License v3.0 6 votes vote down vote up
def describe_transfers(translist: list, getter):
    """

    :param translist:
    :type translist:
    :param getter:
    :type getter:
    :return:
    :rtype:
    """
    described = []
    for transitem in translist:
        transobject = await getter(int(transitem[0])) if inspect.isawaitable(getter) else getter(int(transitem[0]))
        transobject = await transobject if inspect.isawaitable(transobject) else transobject
        if transobject:
            addition = [transobject.name, transitem[1]]
        else:
            addition = transitem
        described.append(addition)
    return described 
Example #8
Source File: evaluate.py    From apex-sigma-core with GNU General Public License v3.0 6 votes vote down vote up
def evaluate(_cmd, pld):
    """
    :param _cmd: The command object referenced in the command.
    :type _cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    if pld.args:
        try:
            execution = " ".join(pld.args)
            output = eval(execution)
            if inspect.isawaitable(output):
                output = await output
            response = ok('Executed')
            response.description = f'```py\n{output}\n```'
        except Exception as e:
            response = error('Error')
            response.description = f'```py\n{e}\n```'
    else:
        response = error('Nothing inputted.')
    await pld.msg.channel.send(embed=response) 
Example #9
Source File: filters.py    From aioalice with MIT License 6 votes vote down vote up
def check_filter(filter_, args):
    """
    Helper for executing filter

    :param filter_:
    :param args:
    :param kwargs:
    :return:
    """
    if not callable(filter_):
        raise TypeError(f'Filter must be callable and/or awaitable! Error with {filter_}')

    if inspect.isawaitable(filter_) or inspect.iscoroutinefunction(filter_):
        return await filter_(*args)
    else:
        return filter_(*args) 
Example #10
Source File: _tasks_async.py    From peeringdb-py with Apache License 2.0 6 votes vote down vote up
def wrap_generator(func):
    """
    Decorator to convert a generator function to an async function which collects
    and returns generator results, returning a list if there are multiple results
    """

    async def _wrapped(*a, **k):
        r, ret = None, []
        gen = func(*a, **k)
        while True:
            try:
                item = gen.send(r)
            except StopIteration:
                break
            if inspect.isawaitable(item):
                r = await item
            else:
                r = item
            ret.append(r)

        if len(ret) == 1:
            return ret.pop()
        return ret

    return _wrapped 
Example #11
Source File: tasks.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def ensure_future(coro_or_future, *, loop=None):
    """Wrap a coroutine or an awaitable in a future.

    If the argument is a Future, it is returned directly.
    """
    if isinstance(coro_or_future, futures.Future):
        if loop is not None and loop is not coro_or_future._loop:
            raise ValueError('loop argument must agree with Future')
        return coro_or_future
    elif coroutines.iscoroutine(coro_or_future):
        if loop is None:
            loop = events.get_event_loop()
        task = loop.create_task(coro_or_future)
        if task._source_traceback:
            del task._source_traceback[-1]
        return task
    elif compat.PY35 and inspect.isawaitable(coro_or_future):
        return ensure_future(_wrap_awaitable(coro_or_future), loop=loop)
    else:
        raise TypeError('A Future, a coroutine or an awaitable is required') 
Example #12
Source File: test_inspect.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_isawaitable(self):
        def gen(): yield
        self.assertFalse(inspect.isawaitable(gen()))

        coro = coroutine_function_example(1)
        gen_coro = gen_coroutine_function_example(1)

        self.assertTrue(inspect.isawaitable(coro))
        self.assertTrue(inspect.isawaitable(gen_coro))

        class Future:
            def __await__():
                pass
        self.assertTrue(inspect.isawaitable(Future()))
        self.assertFalse(inspect.isawaitable(Future))

        class NotFuture: pass
        not_fut = NotFuture()
        not_fut.__await__ = lambda: None
        self.assertFalse(inspect.isawaitable(not_fut))

        coro.close(); gen_coro.close() # silence warnings 
Example #13
Source File: FastTelethon.py    From TG-UserBot with GNU General Public License v3.0 6 votes vote down vote up
def download_file(
    self: TelegramClient, location: TypeLocation,
    out: BinaryIO, progress_callback: callable = None
) -> BinaryIO:
    size = location.size
    dc_id, location = utils.get_input_location(location)
    # We lock the transfers because telegram has connection count limits
    downloader = ParallelTransferrer(self, dc_id)
    downloaded = downloader.download(location, size)
    async for x in downloaded:
        out.write(x)
        if progress_callback:
            r = progress_callback(out.tell(), size)
            if inspect.isawaitable(r):
                await r

    return out 
Example #14
Source File: tasks.py    From Imogen with MIT License 6 votes vote down vote up
def ensure_future(coro_or_future, *, loop=None):
    """Wrap a coroutine or an awaitable in a future.

    If the argument is a Future, it is returned directly.
    """
    if coroutines.iscoroutine(coro_or_future):
        if loop is None:
            loop = events.get_event_loop()
        task = loop.create_task(coro_or_future)
        if task._source_traceback:
            del task._source_traceback[-1]
        return task
    elif futures.isfuture(coro_or_future):
        if loop is not None and loop is not futures._get_loop(coro_or_future):
            raise ValueError('loop argument must agree with Future')
        return coro_or_future
    elif inspect.isawaitable(coro_or_future):
        return ensure_future(_wrap_awaitable(coro_or_future), loop=loop)
    else:
        raise TypeError('An asyncio.Future, a coroutine or an awaitable is '
                        'required') 
Example #15
Source File: evaluators.py    From TG-UserBot with GNU General Public License v3.0 5 votes vote down vote up
def evaluate(event: NewMessage.Event) -> None:
    """
    Evaluate Python expressions in the running script.


    **{prefix}eval (expression)**
        **Example:** `{prefix}eval 1+1`
    """
    expression = event.matches[0].group(1).strip()
    reply = await event.get_reply_message()
    if not expression:
        await event.answer("__Evaluated the void.__")
        return

    try:
        result = await meval(
            expression, globals(), client=client, event=event, reply=reply
        )
    except Exception as e:
        await event.answer(
            f"```{await client.get_traceback(e)}```", reply=True
        )
        return

    extra = await get_chat_link(event, event.id)
    if result:
        if hasattr(result, 'stringify'):
            if inspect.isawaitable(result):
                result = await result.stringify()
            else:
                result = result.stringify()
    result = str(result) if result else "Success?"
    await event.answer(
        "```" + result + "```",
        log=("eval", f"Successfully evaluated {expression} in {extra}!"),
        reply=True
    ) 
Example #16
Source File: asyncsupport.py    From Building-Recommendation-Systems-with-Python with MIT License 5 votes vote down vote up
def auto_await(value):
    if inspect.isawaitable(value):
        return await value
    return value 
Example #17
Source File: async_utils.py    From gd.py with MIT License 5 votes vote down vote up
def wait(
    *fs: Iterable[Coroutine],
    loop: Optional[asyncio.AbstractEventLoop] = None,
    timeout: Optional[Union[float, int]] = None,
    return_when: str = "ALL_COMPLETED",
) -> Tuple[Set[asyncio.Future], Set[asyncio.Future]]:
    """A function that is calling :func:`asyncio.wait`.

    Used for less imports inside and outside of this library.

    Wait for the Futures and coroutines given by fs to complete.

    The sequence futures must not be empty.

    Coroutines will be wrapped in Tasks.

    Returns two sets of Future: (done, pending).

    Usage:

    .. code-block:: python3

        done, pending = await gd.utils.wait(fs)

    .. note::

        This does not raise :exc:`TimeoutError`! Futures that aren't done
        when the timeout occurs are returned in the second set.
    """
    if len(fs) == 1:
        maybe_aw = fs[0]
        if not inspect.isawaitable(maybe_aw):
            fs = maybe_aw

    return await asyncio.wait(fs, loop=loop, timeout=timeout, return_when=return_when) 
Example #18
Source File: messaging.py    From CEX.IO-Client-Python3.5 with MIT License 5 votes vote down vote up
def is_awaitable(obj):
		# There is no single method which can answer in any case, should wait or not - so need to create one
		# for the suspected cases : func, coro, gen-coro, future,
		#                           class with sync __call__, class with async __call__,
		#                           sync method, async method
		if inspect.isawaitable(obj) or inspect.iscoroutinefunction(obj) or inspect.iscoroutine(obj):
			return True
		elif inspect.isgeneratorfunction(obj):
			return True
		elif CallChain.is_user_defined_class(obj):
			if hasattr(obj, '__call__'):
				return CallChain.is_awaitable(obj.__call__)
			return False
		else:
			return False 
Example #19
Source File: asyncsupport.py    From planespotter with MIT License 5 votes vote down vote up
def auto_await(value):
    if inspect.isawaitable(value):
        return await value
    return value 
Example #20
Source File: completer.py    From stig with GNU General Public License v3.0 5 votes vote down vote up
def _get_candidates_wrapper(self, args):
        async def maybe_await(x):
            while inspect.isawaitable(x):
                x = await x
            return x

        cands = await maybe_await(self._get_candidates(args))
        if cands is None:
            cats = ()
        elif isinstance(cands, Candidates):
            cats = (cands,)
        elif isinstance(cands, (abc.Iterable, abc.Iterator)):
            def flatten(iters):
                # Only yield Candidates instances
                for item in iters:
                    if item is None:
                        pass
                    elif isinstance(item, Candidates):
                        yield item
                    elif isinstance(item, abc.Iterable) and not isinstance(item, str):
                        yield from flatten(item)
                    else:
                        raise RuntimeError('Not a Candidates object or iterable of Candidates objects: %r' % (item,))
            cats = tuple(flatten(cands))
        else:
            raise RuntimeError('Invalid candidates: %r' % (cands,))

        # Include current user input (this is filled in later when the current
        # command line is parsed)
        return Categories(SingleCandidate(''), *cats) 
Example #21
Source File: debug.py    From Discord-SelfBot with MIT License 5 votes vote down vote up
def debug(self, ctx, *, code: str):
        """Single line Python debug.."""
        code = code.strip('` ')
        env = {
            'bot': self.bot,
            'say': ctx.send,
            'ctx': ctx,
            'message': ctx.message,
            'guild': ctx.guild,
            'server': ctx.guild,
            'channel': ctx.channel,
            'author': ctx.message.author,
            'me': ctx.message.author,
            'self': self
        }

        env.update(self.env)
        env.update(globals())
        try:
            result = eval(code, env)
            if inspect.isawaitable(result):
                result = await result
        except Exception as e:
            try:
                await ctx.message.add_reaction('\N{HEAVY MULTIPLICATION X}')
            except:
                pass
            await self.do_send(ctx=ctx, description="SelfBot Python Debug", value=str(type(e).__name__) + ': ' + str(e), filename='debug.py')
            return
        try:
            await ctx.message.add_reaction('\N{HEAVY CHECK MARK}')
        except:
            pass
        await self.do_send(ctx=ctx, description="SelfBot Python Debug", value=str(result), filename='debug.py') 
Example #22
Source File: asyncsupport.py    From Building-Recommendation-Systems-with-Python with MIT License 5 votes vote down vote up
def auto_await(value):
    if inspect.isawaitable(value):
        return await value
    return value 
Example #23
Source File: connection.py    From aredis with MIT License 5 votes vote down vote up
def connect(self):
        try:
            await self._connect()
        except Exception as exc:
            raise ConnectionError()
        # run any user callbacks. right now the only internal callback
        # is for pubsub channel/pattern resubscription
        for callback in self._connect_callbacks:
            task = callback(self)
            # typing.Awaitable is not available in Python3.5
            # so use inspect.isawaitable instead
            # according to issue https://github.com/NoneGG/aredis/issues/77
            if inspect.isawaitable(task):
                await task 
Example #24
Source File: thenables.py    From graphene with MIT License 5 votes vote down vote up
def maybe_thenable(obj, on_resolve):
    """
    Execute a on_resolve function once the thenable is resolved,
    returning the same type of object inputed.
    If the object is not thenable, it should return on_resolve(obj)
    """
    if isawaitable(obj):
        return await_and_execute(obj, on_resolve)

    # If it's not awaitable, return the function executed over the object
    return on_resolve(obj) 
Example #25
Source File: asyncsupport.py    From pySINDy with MIT License 5 votes vote down vote up
def auto_await(value):
    if inspect.isawaitable(value):
        return await value
    return value 
Example #26
Source File: program.py    From mautrix-python with Mozilla Public License 2.0 5 votes vote down vote up
def _add_actions(to: TaskList, add: Tuple[NewTask, ...]) -> TaskList:
        for item in add:
            if inspect.isawaitable(item):
                if isinstance(to, list):
                    to.append(item)
                else:
                    to = chain(to, [item])
            elif isinstance(item, list):
                if isinstance(to, list):
                    to += item
                else:
                    to = chain(to, item)
            else:
                to = chain(to, item)
        return to 
Example #27
Source File: asyncsupport.py    From OpenXR-SDK-Source with Apache License 2.0 5 votes vote down vote up
def auto_await(value):
    if inspect.isawaitable(value):
        return await value
    return value 
Example #28
Source File: extension.py    From sanic-cors with MIT License 5 votes vote down vote up
def route_wrapper(self, route, req, context, request_args, request_kw,
                            *decorator_args, **decorator_kw):
        _ = decorator_kw.pop('with_context')  # ignore this.
        _options = decorator_kw
        options = get_cors_options(context.app, _options)
        if options.get('automatic_options', True) and req.method == 'OPTIONS':
            resp = response.HTTPResponse()
        else:
            resp = route(req, *request_args, **request_kw)
            while isawaitable(resp):
                resp = await resp
            # resp can be `None` or `[]` if using Websockets
            if not resp:
                return None
        try:
            request_context = context.request[id(req)]
        except (AttributeError, LookupError):
            if SANIC_19_9_0 <= SANIC_VERSION:
                request_context = req.ctx
            else:
                request_context = None
        set_cors_headers(req, resp, request_context, options)
        if request_context is not None:
            setattr(request_context, SANIC_CORS_EVALUATED, "1")
        else:
            context.log(logging.DEBUG, "Cannot access a sanic request "
                        "context. Has request started? Is request ended?")
        return resp 
Example #29
Source File: asyncsupport.py    From pipenv with MIT License 5 votes vote down vote up
def auto_await(value):
    if inspect.isawaitable(value):
        return await value
    return value 
Example #30
Source File: spider.py    From ruia with Apache License 2.0 5 votes vote down vote up
def _run_response_middleware(self, request: Request, response: Response):
        if self.middleware.response_middleware:
            for middleware in self.middleware.response_middleware:
                if callable(middleware):
                    try:
                        aws_middleware_func = middleware(self, request, response)
                        if isawaitable(aws_middleware_func):
                            await aws_middleware_func
                        else:
                            self.logger.error(
                                f"<Middleware {middleware.__name__}: must be a coroutine function"
                            )
                    except Exception as e:
                        self.logger.error(f"<Middleware {middleware.__name__}: {e}")