Python inspect.isasyncgenfunction() Examples

The following are 21 code examples of inspect.isasyncgenfunction(). 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: utils.py    From fastapi with MIT License 6 votes vote down vote up
def solve_generator(
    *, call: Callable, stack: AsyncExitStack, sub_values: Dict[str, Any]
) -> Any:
    if is_gen_callable(call):
        cm = contextmanager_in_threadpool(contextmanager(call)(**sub_values))
    elif is_async_gen_callable(call):
        if not inspect.isasyncgenfunction(call):
            # asynccontextmanager from the async_generator backfill pre python3.7
            # does not support callables that are not functions or methods.
            # See https://github.com/python-trio/async_generator/issues/32
            #
            # Expand the callable class into its __call__ method before decorating it.
            # This approach will work on newer python versions as well.
            call = getattr(call, "__call__", None)
        cm = asynccontextmanager(call)(**sub_values)
    return await stack.enter_async_context(cm) 
Example #2
Source File: base.py    From dffml with MIT License 6 votes vote down vote up
def _imp(cls, loaded):
        """
        Returns the operation implemention from a loaded entrypoint object, or
        None if its not an operation implemention or doesn't have the imp
        parameter which is an operation implemention.
        """
        for obj in [getattr(loaded, "imp", None), loaded]:
            if inspect.isclass(obj) and issubclass(obj, cls):
                return obj
        if (
            inspect.isfunction(loaded)
            or inspect.isgeneratorfunction(loaded)
            or inspect.iscoroutinefunction(loaded)
            or inspect.isasyncgenfunction(loaded)
        ):
            return op(loaded).imp
        return None 
Example #3
Source File: local_database.py    From parsec-cloud with GNU Affero General Public License v3.0 6 votes vote down vote up
def protect_with_lock(fn):
    """Use as a decorator to protect an async method with `self._lock`.

    Also works with async gen method so it can be used for `open_cursor`.
    """

    if inspect.isasyncgenfunction(fn):

        @functools.wraps(fn)
        async def wrapper(self, *args, **kwargs):
            async with self._lock:
                async for item in fn.__get__(self)(*args, **kwargs):
                    yield item

    else:
        assert inspect.iscoroutinefunction(fn)

        @functools.wraps(fn)
        async def wrapper(self, *args, **kwargs):
            async with self._lock:
                return await fn.__get__(self)(*args, **kwargs)

    return wrapper 
Example #4
Source File: server.py    From aiotools with MIT License 5 votes vote down vote up
def __init__(self, func: Callable[..., Any], args, kwargs):
        if not inspect.isasyncgenfunction(func):
            raise RuntimeError('Context manager function must be '
                               'an async-generator')
        self._agen = func(*args, **kwargs)
        self.func = func
        self.args = args
        self.kwargs = kwargs
        self.yield_return = None 
Example #5
Source File: hints.py    From vibora with MIT License 5 votes vote down vote up
def __init__(self, stream: Callable, status_code: int = 200, headers: dict = None, cookies: list = None,
                 complete_timeout: int = 30, chunk_timeout: int = 10):
        super().__init__(b'', status_code=status_code, headers=headers, cookies=cookies)
        if not callable(stream):
            raise ValueError('StreamingResponse "stream" must be a callable.')
        self.stream = stream
        self.content = b''
        self.is_async = isasyncgenfunction(stream)
        if 'Content-Length' in self.headers:
            self.chunked = False
        else:
            self.chunked = True
            self.headers['Transfer-Encoding'] = 'chunked'
        self.complete_timeout = complete_timeout
        self.chunk_timeout = chunk_timeout 
Example #6
Source File: helpers.py    From vibora with MIT License 5 votes vote down vote up
def smart_iter(element):
    if isasyncgen(element) or isasyncgenfunction(element):
        async for x in element:
            yield x
    else:
        for x in element:
            yield x 
Example #7
Source File: __init__.py    From pdoc with GNU Affero General Public License v3.0 5 votes vote down vote up
def _is_async(self):
        """
        Returns whether is function is asynchronous, either as a coroutine or an async
        generator.
        """
        try:
            # Both of these are required because coroutines aren't classified as async
            # generators and vice versa.
            obj = inspect.unwrap(self.obj)
            return (inspect.iscoroutinefunction(obj) or
                    inspect.isasyncgenfunction(obj))
        except AttributeError:
            return False 
Example #8
Source File: pool.py    From lightbus with Apache License 2.0 5 votes vote down vote up
def __getattr__(self, item):
        async def fn_pool_wrapper(*args, **kwargs):
            async with self as transport:
                return await getattr(transport, item)(*args, **kwargs)

        async def gen_pool_wrapper(*args, **kwargs):
            async with self as transport:
                async for value in getattr(transport, item)(*args, **kwargs):
                    yield value

        attr = getattr(self.transport_class, item, None)

        if not attr:
            raise AttributeError(
                f"Neither the transport pool {repr(self)} nor the transport with class "
                f"{repr(self.transport_class)} has an attribute named {item}"
            )
        elif item[0] == "_":
            raise CannotProxyPrivateMethod(
                f"Cannot proxy private method calls to transport. Use the pool's async context or "
                f"checkout() method if you really need to access private methods. (Private methods "
                f"are ones whose name starts with an underscore)"
            )
        elif not callable(attr):
            raise CannotProxyProperty(
                f"Cannot proxy property access on transports. Use the pool's async context or "
                f"checkout() method to get access to a transport directly."
            )
        else:
            if iscoroutinefunction(attr):
                return fn_pool_wrapper
            elif isasyncgenfunction(attr):
                return gen_pool_wrapper
            else:
                raise CannotProxySynchronousMethod(
                    f"{self.transport_class.__name__}.{item}() is synchronous "
                    f"and must be accessed directly and not via the pool"
                ) 
Example #9
Source File: statically.py    From statically with MIT License 5 votes vote down vote up
def typed(obj):
    """Compiles a function or class with cython.

    Use annotations for static type declarations. Example:

        import statically

        @statically.typed
        def add_two(x: int) -> int:
            two: int = 2
            return x + two
    """
    if not _can_cython_inline():
        return obj
    elif has_async_gen_fun and inspect.isasyncgenfunction(obj):
        raise TypeError("Async generator funcions are not supported.")

    source = _get_source_code(obj)
    frame = inspect.currentframe().f_back
    if inspect.isclass(obj):
        locals_ = frame.f_locals
    else:
        locals_ = _get_outer_variables(obj)
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        compiled = cython.inline(source, locals=locals_,
                                 globals=frame.f_globals, quiet=True)
        return compiled[obj.__name__] 
Example #10
Source File: fixtures.py    From ward with MIT License 5 votes vote down vote up
def is_async_generator_fixture(self):
        return inspect.isasyncgenfunction(inspect.unwrap(self.fn)) 
Example #11
Source File: compilation.py    From jishaku with MIT License 5 votes vote down vote up
def traverse(self, func):
        """
        Traverses an async function or generator, yielding each result.

        This function is private. The class should be used as an iterator instead of using this method.
        """

        if inspect.isasyncgenfunction(func):
            async for send, result in AsyncSender(func(*self.args)):
                send((yield result))
        else:
            yield await func(*self.args) 
Example #12
Source File: compilation.py    From jishaku with MIT License 5 votes vote down vote up
def traverse(self, func):
        """
        Traverses an async function or generator, yielding each result.

        This function is private. The class should be used as an iterator instead of using this method.
        """

        if inspect.isasyncgenfunction(func):
            async for send, result in AsyncSender(func(*self.args)):
                send((yield result))
        else:
            yield await func(*self.args) 
Example #13
Source File: context.py    From aiotools with MIT License 5 votes vote down vote up
def __init__(self, func: Callable[..., Any], args, kwargs):
            if not inspect.isasyncgenfunction(func):
                raise RuntimeError('Context manager function must be '
                                   'an async-generator')
            self._agen = func(*args, **kwargs)
            self.func = func
            self.args = args
            self.kwargs = kwargs 
Example #14
Source File: conftest.py    From ldapauthenticator with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def pytest_collection_modifyitems(items):
    """add asyncio marker to all async tests"""
    for item in items:
        if inspect.iscoroutinefunction(item.obj):
            item.add_marker("asyncio")
        if hasattr(inspect, "isasyncgenfunction"):
            # double-check that we aren't mixing yield and async def
            assert not inspect.isasyncgenfunction(item.obj) 
Example #15
Source File: __init__.py    From python-aspectlib with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def isasyncfunction(obj):
        if isasyncgenfunction is None:
            return iscoroutinefunction(obj)
        else:
            return isasyncgenfunction(obj) or iscoroutinefunction(obj) 
Example #16
Source File: py35support.py    From python-aspectlib with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def decorate_advising_asyncgenerator_py35(advising_function, cutpoint_function, bind):
    assert isasyncgenfunction(cutpoint_function) or iscoroutinefunction(cutpoint_function)

    async def advising_asyncgenerator_wrapper_py35(*args, **kwargs):
        if bind:
            advisor = advising_function(cutpoint_function, *args, **kwargs)
        else:
            advisor = advising_function(*args, **kwargs)
        if not isgenerator(advisor):
            raise ExpectedGenerator("advising_function %s did not return a generator." % advising_function)
        try:
            advice = next(advisor)
            while True:
                logdebug('Got advice %r from %s', advice, advising_function)
                if advice is Proceed or advice is None or isinstance(advice, Proceed):
                    if isinstance(advice, Proceed):
                        args = advice.args
                        kwargs = advice.kwargs
                    gen = cutpoint_function(*args, **kwargs)
                    try:
                        result = await gen
                    except BaseException:
                        advice = advisor.throw(*sys.exc_info())
                    else:
                        try:
                            advice = advisor.send(result)
                        except StopIteration:
                            return result
                    finally:
                        gen.close()
                elif advice is Return:
                    return
                elif isinstance(advice, Return):
                    return advice.value
                else:
                    raise UnacceptableAdvice("Unknown advice %s" % advice)
        finally:
            advisor.close()
    return mimic(advising_asyncgenerator_wrapper_py35, cutpoint_function) 
Example #17
Source File: cmd.py    From dffml with MIT License 5 votes vote down vote up
def do_run(self):
        async with self:
            if inspect.isasyncgenfunction(self.run):
                return [res async for res in self.run()]
            else:
                return await self.run() 
Example #18
Source File: compat.py    From pytest with MIT License 5 votes vote down vote up
def is_async_function(func: object) -> bool:
    """Return True if the given function seems to be an async function or async generator"""
    return iscoroutinefunction(func) or (
        sys.version_info >= (3, 6) and inspect.isasyncgenfunction(func)
    ) 
Example #19
Source File: element_updater.py    From awe with MIT License 5 votes vote down vote up
def add(self, updater):
        assert isinstance(updater, Updater)
        fn = updater.updater
        if six.PY3 and inspect.isasyncgenfunction(fn):
            self.async_loop.call_soon_threadsafe(self._add_async_generator_updater, updater)
        elif six.PY3 and inspect.iscoroutinefunction(fn):
            self.async_loop.call_soon_threadsafe(self._add_async_updater, updater)
        elif inspect.isgeneratorfunction(fn):
            self._add_generator_updater(updater)
        elif callable(fn):
            self._add_callable_updater(updater)
        else:
            raise ValueError('Invalid updater: {}'.format(fn)) 
Example #20
Source File: utils.py    From fastapi with MIT License 5 votes vote down vote up
def is_async_gen_callable(call: Callable) -> bool:
    if inspect.isasyncgenfunction(call):
        return True
    call = getattr(call, "__call__", None)
    return inspect.isasyncgenfunction(call) 
Example #21
Source File: reflect.py    From synapse with Apache License 2.0 4 votes vote down vote up
def getShareInfo(item):
    '''
    Get a dictionary of special annotations for a Telepath Proxy.

    Args:
        item:  Item to inspect.

    Notes:
        This will set the ``_syn_telemeth`` attribute on the item
        and the items class, so this data is only computed once.

    Returns:
        dict: A dictionary of methods requiring special handling by the proxy.
    '''
    key = f'_syn_sharinfo_{item.__class__.__module__}_{item.__class__.__qualname__}'
    info = getattr(item, key, None)
    if info is not None:
        return info

    meths = {}
    info = {'meths': meths,
            'syn:version': s_version.version,
            'classes': getClsNames(item),
            }

    for name in dir(item):

        if name.startswith('_'):
            continue

        attr = getattr(item, name, None)
        if not callable(attr):
            continue

        # We know we can cleanly unwrap these functions
        # for asyncgenerator inspection.
        wrapped = getattr(attr, '__syn_wrapped__', None)
        if wrapped in unwraps:
            real = inspect.unwrap(attr)
            if inspect.isasyncgenfunction(real):
                meths[name] = {'genr': True}
                continue

        if inspect.isasyncgenfunction(attr):
            meths[name] = {'genr': True}

    try:
        setattr(item, key, info)
    except Exception:  # pragma: no cover
        logger.exception(f'Failed to set magic on {item}')

    try:
        setattr(item.__class__, key, info)
    except Exception:  # pragma: no cover
        logger.exception(f'Failed to set magic on {item.__class__}')

    return info