本文整理汇总了Python中inspect.iscoroutinefunction方法的典型用法代码示例。如果您正苦于以下问题:Python inspect.iscoroutinefunction方法的具体用法?Python inspect.iscoroutinefunction怎么用?Python inspect.iscoroutinefunction使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类inspect
的用法示例。
在下文中一共展示了inspect.iscoroutinefunction方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import iscoroutinefunction [as 别名]
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)
示例2: pytest_pyfunc_call
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import iscoroutinefunction [as 别名]
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
示例3: wrap_view
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import iscoroutinefunction [as 别名]
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
示例4: error
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import iscoroutinefunction [as 别名]
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
示例5: before_loop
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import iscoroutinefunction [as 别名]
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
示例6: error
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import iscoroutinefunction [as 别名]
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
示例7: mirror_sync_methods
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import iscoroutinefunction [as 别名]
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)))
示例8: check_filter
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import iscoroutinefunction [as 别名]
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)
示例9: purerpc_channel
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import iscoroutinefunction [as 别名]
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
示例10: start
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import iscoroutinefunction [as 别名]
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()
示例11: _iter_methods
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import iscoroutinefunction [as 别名]
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
示例12: fetch_callback
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import iscoroutinefunction [as 别名]
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
示例13: test_oneline_defs
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import iscoroutinefunction [as 别名]
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']))
示例14: test_iscoroutine
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import iscoroutinefunction [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
示例15: _imp
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import iscoroutinefunction [as 别名]
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