Python inspect.iscoroutinefunction() Examples
The following are 30
code examples of inspect.iscoroutinefunction().
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: app.py From datasette with Apache License 2.0 | 6 votes |
def wrap_view(view_fn, datasette): async def async_view_fn(request, send): if inspect.iscoroutinefunction(view_fn): response = await async_call_with_supported_arguments( view_fn, scope=request.scope, receive=request.receive, send=send, request=request, datasette=datasette, ) else: response = call_with_supported_arguments( view_fn, scope=request.scope, receive=request.receive, send=send, request=request, datasette=datasette, ) if response is not None: return response return async_view_fn
Example #2
Source File: request.py From ruia with Apache License 2.0 | 6 votes |
def fetch_callback( self, sem: Semaphore ) -> Tuple[AsyncGeneratorType, Response]: """ Request the target url and then call the callback function :param sem: Semaphore :return: Tuple[AsyncGeneratorType, Response] """ try: async with sem: response = await self.fetch() except Exception as e: response = None self.logger.error(f"<Error: {self.url} {e}>") if self.callback is not None: if iscoroutinefunction(self.callback): callback_result = await self.callback(response) else: callback_result = self.callback(response) else: callback_result = None return callback_result, response
Example #3
Source File: __init__.py From discord.py with MIT License | 6 votes |
def error(self, coro): """A decorator that registers a coroutine to be called if the task encounters an unhandled exception. The coroutine must take only one argument the exception raised (except ``self`` in a class context). By default this prints to :data:`sys.stderr` however it could be overridden to have a different implementation. .. versionadded:: 1.4 Parameters ------------ coro: :ref:`coroutine <coroutine>` The coroutine to register in the event of an unhandled exception. Raises ------- TypeError The function was not a coroutine. """ if not inspect.iscoroutinefunction(coro): raise TypeError('Expected coroutine function, received {0.__name__!r}.'.format(type(coro))) self._error = coro return coro
Example #4
Source File: asyn.py From filesystem_spec with BSD 3-Clause "New" or "Revised" License | 6 votes |
def mirror_sync_methods(obj): """Populate sync and async methods for obj For each method will create a sync version if the name refers to an async method (coroutine) and there is no override in the child class; will create an async method for the corresponding sync method if there is no implementation. Uses the methods specified in - async_methods: the set that an implementation is expected to provide - default_async_methods: that can be derived from their sync version in AbstractFileSystem - AsyncFileSystem: async-specific default implementations """ from fsspec import AbstractFileSystem for method in async_methods + default_async_methods + dir(AsyncFileSystem): smethod = method[1:] if private.match(method): if inspect.iscoroutinefunction(getattr(obj, method, None)) and getattr( obj, smethod, False ).__func__ is getattr(AbstractFileSystem, smethod): setattr(obj, smethod, sync_wrapper(getattr(obj, method), obj=obj)) elif hasattr(obj, smethod) and inspect.ismethod(getattr(obj, smethod)): setattr(obj, method, async_wrapper(getattr(obj, smethod)))
Example #5
Source File: __init__.py From discord.py with MIT License | 6 votes |
def before_loop(self, coro): """A decorator that registers a coroutine to be called before the loop starts running. This is useful if you want to wait for some bot state before the loop starts, such as :meth:`discord.Client.wait_until_ready`. The coroutine must take no arguments (except ``self`` in a class context). Parameters ------------ coro: :ref:`coroutine <coroutine>` The coroutine to register before the loop runs. Raises ------- TypeError The function was not a coroutine. """ if not inspect.iscoroutinefunction(coro): raise TypeError('Expected coroutine function, received {0.__name__!r}.'.format(type(coro))) self._before_loop = coro return coro
Example #6
Source File: server.py From edgedb with Apache License 2.0 | 6 votes |
def _iter_methods(bases, ns): for base in bases: for methname in dir(base): if not methname.startswith('test_'): continue meth = getattr(base, methname) if not inspect.iscoroutinefunction(meth): continue yield methname, meth for methname, meth in ns.items(): if not methname.startswith('test_'): continue if not inspect.iscoroutinefunction(meth): continue yield methname, meth
Example #7
Source File: test_coroutines.py From Fluid-Designer with GNU General Public License v3.0 | 6 votes |
def test_oneline_defs(self): buf = [] for i in range(500): buf.append('def i{i}(): return {i}'.format(i=i)) buf = '\n'.join(buf) # Test that 500 consequent, one-line defs is OK ns = {} exec(buf, ns, ns) self.assertEqual(ns['i499'](), 499) # Test that 500 consequent, one-line defs *and* # one 'async def' following them is OK buf += '\nasync def foo():\n return' ns = {} exec(buf, ns, ns) self.assertEqual(ns['i499'](), 499) self.assertTrue(inspect.iscoroutinefunction(ns['foo']))
Example #8
Source File: filters.py From aioalice with MIT License | 6 votes |
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 #9
Source File: test_inspect.py From Fluid-Designer with GNU General Public License v3.0 | 6 votes |
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 #10
Source File: core.py From discord.py with MIT License | 6 votes |
def error(self, coro): """A decorator that registers a coroutine as a local error handler. A local error handler is an :func:`.on_command_error` event limited to a single command. However, the :func:`.on_command_error` is still invoked afterwards as the catch-all. Parameters ----------- coro: :ref:`coroutine <coroutine>` The coroutine to register as the local error handler. Raises ------- TypeError The coroutine passed is not actually a coroutine. """ if not asyncio.iscoroutinefunction(coro): raise TypeError('The error handler must be a coroutine.') self.on_error = coro return coro
Example #11
Source File: decorator.py From nzb-subliminal with GNU General Public License v3.0 | 6 votes |
def create(cls, obj, body, evaldict, defaults=None, doc=None, module=None, addsource=True, **attrs): """ Create a function from the strings name, signature and body. evaldict is the evaluation dictionary. If addsource is true an attribute __source__ is added to the result. The attributes attrs are added, if any. """ if isinstance(obj, str): # "name(signature)" name, rest = obj.strip().split('(', 1) signature = rest[:-1] # strip a right parens func = None else: # a function name = None signature = None func = obj self = cls(func, name, signature, defaults, doc, module) ibody = '\n'.join(' ' + line for line in body.splitlines()) caller = evaldict.get('_call_') # when called from `decorate` if caller and iscoroutinefunction(caller): body = ('async def %(name)s(%(signature)s):\n' + ibody).replace( 'return', 'return await') else: body = 'def %(name)s(%(signature)s):\n' + ibody return self.make(body, evaldict, addsource, **attrs)
Example #12
Source File: conftest.py From aioredis with MIT License | 6 votes |
def pytest_pyfunc_call(pyfuncitem): """ Run asyncio marked test functions in an event loop instead of a normal function call. """ if inspect.iscoroutinefunction(pyfuncitem.obj): marker = pyfuncitem.get_closest_marker('timeout') if marker is not None and marker.args: timeout = marker.args[0] else: timeout = 15 funcargs = pyfuncitem.funcargs loop = funcargs['loop'] testargs = {arg: funcargs[arg] for arg in pyfuncitem._fixtureinfo.argnames} loop.run_until_complete( _wait_coro(pyfuncitem.obj, testargs, timeout=timeout)) return True
Example #13
Source File: decorator.py From pySINDy with MIT License | 6 votes |
def create(cls, obj, body, evaldict, defaults=None, doc=None, module=None, addsource=True, **attrs): """ Create a function from the strings name, signature and body. evaldict is the evaluation dictionary. If addsource is true an attribute __source__ is added to the result. The attributes attrs are added, if any. """ if isinstance(obj, str): # "name(signature)" name, rest = obj.strip().split('(', 1) signature = rest[:-1] # strip a right parens func = None else: # a function name = None signature = None func = obj self = cls(func, name, signature, defaults, doc, module) ibody = '\n'.join(' ' + line for line in body.splitlines()) caller = evaldict.get('_call_') # when called from `decorate` if caller and iscoroutinefunction(caller): body = ('async def %(name)s(%(signature)s):\n' + ibody).replace( 'return', 'return await') else: body = 'def %(name)s(%(signature)s):\n' + ibody return self.make(body, evaldict, addsource, **attrs)
Example #14
Source File: decorator.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
def create(cls, obj, body, evaldict, defaults=None, doc=None, module=None, addsource=True, **attrs): """ Create a function from the strings name, signature and body. evaldict is the evaluation dictionary. If addsource is true an attribute __source__ is added to the result. The attributes attrs are added, if any. """ if isinstance(obj, str): # "name(signature)" name, rest = obj.strip().split('(', 1) signature = rest[:-1] # strip a right parens func = None else: # a function name = None signature = None func = obj self = cls(func, name, signature, defaults, doc, module) ibody = '\n'.join(' ' + line for line in body.splitlines()) caller = evaldict.get('_call_') # when called from `decorate` if caller and iscoroutinefunction(caller): body = ('async def %(name)s(%(signature)s):\n' + ibody).replace( 'return', 'return await') else: body = 'def %(name)s(%(signature)s):\n' + ibody return self.make(body, evaldict, addsource, **attrs)
Example #15
Source File: test_utils.py From purerpc with Apache License 2.0 | 6 votes |
def purerpc_channel(port_fixture_name, channel_arg_name="channel"): def decorator(corofunc): if not inspect.iscoroutinefunction(corofunc): raise TypeError("Expected coroutine function") @forge.compose( forge.copy(corofunc), forge.modify(channel_arg_name, name=port_fixture_name, interface_name="port_fixture_value"), ) async def new_corofunc(*, port_fixture_value, **kwargs): import purerpc async with purerpc.insecure_channel("127.0.0.1", port_fixture_value) as channel: await corofunc(**kwargs, channel=channel) return new_corofunc return decorator
Example #16
Source File: decorator.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
def create(cls, obj, body, evaldict, defaults=None, doc=None, module=None, addsource=True, **attrs): """ Create a function from the strings name, signature and body. evaldict is the evaluation dictionary. If addsource is true an attribute __source__ is added to the result. The attributes attrs are added, if any. """ if isinstance(obj, str): # "name(signature)" name, rest = obj.strip().split('(', 1) signature = rest[:-1] # strip a right parens func = None else: # a function name = None signature = None func = obj self = cls(func, name, signature, defaults, doc, module) ibody = '\n'.join(' ' + line for line in body.splitlines()) caller = evaldict.get('_call_') # when called from `decorate` if caller and iscoroutinefunction(caller): body = ('async def %(name)s(%(signature)s):\n' + ibody).replace( 'return', 'return await') else: body = 'def %(name)s(%(signature)s):\n' + ibody return self.make(body, evaldict, addsource, **attrs)
Example #17
Source File: base.py From dffml with MIT License | 6 votes |
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 #18
Source File: quant.py From aioquant with MIT License | 6 votes |
def start(self, config_file=None, entrance_func=None) -> None: """Start the event loop.""" def keyboard_interrupt(s, f): print("KeyboardInterrupt (ID: {}) has been caught. Cleaning up...".format(s)) self.stop() signal.signal(signal.SIGINT, keyboard_interrupt) self._initialize(config_file) if entrance_func: if inspect.iscoroutinefunction(entrance_func): self.loop.create_task(entrance_func()) else: entrance_func() logger.info("start io loop ...", caller=self) self.loop.run_forever()
Example #19
Source File: decorator.py From pySINDy with MIT License | 5 votes |
def iscoroutinefunction(f): return False
Example #20
Source File: request.py From ruia with Apache License 2.0 | 5 votes |
def _retry(self, error_msg): """Manage request""" if self.retry_times > 0: # Sleep to give server a chance to process/cache prior request if self.request_config.get("RETRY_DELAY", 0) > 0: await asyncio.sleep(self.request_config["RETRY_DELAY"]) retry_times = self.request_config.get("RETRIES", 3) - self.retry_times + 1 self.logger.error( f"<Retry url: {self.url}>, Retry times: {retry_times}, Retry message: {error_msg}>" ) self.retry_times -= 1 retry_func = self.request_config.get("RETRY_FUNC") if retry_func and iscoroutinefunction(retry_func): request_ins = await retry_func(weakref.proxy(self)) if isinstance(request_ins, Request): return await request_ins.fetch(delay=False) return await self.fetch(delay=False) else: response = Response( url=self.url, method=self.method, metadata=self.metadata, cookies={}, history=(), headers=None, ) return response
Example #21
Source File: tasks.py From thenextquant with MIT License | 5 votes |
def call_later(cls, func, delay=0, *args, **kwargs): """ Create a coroutine and delay execute, delay time is seconds, default delay time is 0s. Args: func: Asynchronous callback function. delay: Delay time is seconds, default delay time is 0, you can assign a float e.g. 0.5, 2.3, 5.1 ... """ if not inspect.iscoroutinefunction(func): asyncio.get_event_loop().call_later(delay, func, *args) else: def foo(f, *args, **kwargs): asyncio.get_event_loop().create_task(f(*args, **kwargs)) asyncio.get_event_loop().call_later(delay, foo, func, *args)
Example #22
Source File: compat.py From pytest with MIT License | 5 votes |
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 #23
Source File: utils.py From sanic-jwt with MIT License | 5 votes |
def call(fn, *args, **kwargs): if inspect.iscoroutinefunction(fn) or inspect.isawaitable(fn): fn = await fn(*args, **kwargs) elif callable(fn): fn = fn(*args, **kwargs) return fn
Example #24
Source File: utils.py From hypercorn with MIT License | 5 votes |
def _is_asgi_2(app: ASGIFramework) -> bool: if inspect.isclass(app): return True if hasattr(app, "__call__") and inspect.iscoroutinefunction(app.__call__): # type: ignore return False return not inspect.iscoroutinefunction(app)
Example #25
Source File: stats.py From aries-cloudagent-python with Apache License 2.0 | 5 votes |
def __call__(self, fn, groups: Sequence[str] = None): """ Decorate a function or class method. Returns: a wrapped function or coroutine with automatic stats collection """ groups = set(groups) if groups else set() if inspect.iscoroutinefunction(fn): groups.add(fn.__qualname__) return self.wrap_coro(fn, groups) elif inspect.isfunction(fn) or inspect.ismethod(fn): groups.add(fn.__qualname__) return self.wrap_fn(fn, groups) else: raise ValueError(f"Expected function or coroutine, got: {fn}")
Example #26
Source File: element_updater.py From awe with MIT License | 5 votes |
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 #27
Source File: channel.py From indy-plenum with Apache License 2.0 | 5 votes |
def add(self, msg_type: Type, handler: Callable): if iscoroutinefunction(handler): raise ValueError('Router works only with synchronous handlers') RouterBase.add(self, msg_type, handler)
Example #28
Source File: channel.py From indy-plenum with Apache License 2.0 | 5 votes |
def subscribe(self, handler: Callable): if iscoroutinefunction(handler): self._async_handlers.append(handler) else: self._sync_handlers.append(handler)
Example #29
Source File: test_aio.py From prometheus-async with Apache License 2.0 | 5 votes |
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
Example #30
Source File: tasks.py From aioquant with MIT License | 5 votes |
def call_later(cls, func, delay=0, *args, **kwargs): """Create a coroutine and delay execute, delay time is seconds, default delay time is 0s. Args: func: Asynchronous callback function. delay: Delay time is seconds, default delay time is 0, you can assign a float e.g. 0.5, 2.3, 5.1 ... """ if not inspect.iscoroutinefunction(func): asyncio.get_event_loop().call_later(delay, func, *args) else: def foo(f, *args, **kwargs): asyncio.get_event_loop().create_task(f(*args, **kwargs)) asyncio.get_event_loop().call_later(delay, foo, func, *args)