本文整理匯總了Python中types.coroutine方法的典型用法代碼示例。如果您正苦於以下問題:Python types.coroutine方法的具體用法?Python types.coroutine怎麽用?Python types.coroutine使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類types
的用法示例。
在下文中一共展示了types.coroutine方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: sleep
# 需要導入模塊: import types [as 別名]
# 或者: from types import coroutine [as 別名]
def sleep(duration):
"""Return a `.Future` that resolves after the given number of seconds.
When used with ``yield`` in a coroutine, this is a non-blocking
analogue to `time.sleep` (which should not be used in coroutines
because it is blocking)::
yield gen.sleep(0.5)
Note that calling this function on its own does nothing; you must
wait on the `.Future` it returns (usually by yielding it).
.. versionadded:: 4.1
"""
f = Future()
IOLoop.current().call_later(duration, lambda: f.set_result(None))
return f
示例2: _argument_adapter
# 需要導入模塊: import types [as 別名]
# 或者: from types import coroutine [as 別名]
def _argument_adapter(callback):
"""Returns a function that when invoked runs ``callback`` with one arg.
If the function returned by this function is called with exactly
one argument, that argument is passed to ``callback``. Otherwise
the args tuple and kwargs dict are wrapped in an `Arguments` object.
"""
def wrapper(*args, **kwargs):
if kwargs or len(args) > 1:
callback(Arguments(args, kwargs))
elif args:
callback(args[0])
else:
callback(None)
return wrapper
# Convert Awaitables into Futures. It is unfortunately possible
# to have infinite recursion here if those Awaitables assume that
# we're using a different coroutine runner and yield objects
# we don't understand. If that happens, the solution is to
# register that runner's yieldable objects with convert_yielded.
示例3: __init__
# 需要導入模塊: import types [as 別名]
# 或者: from types import coroutine [as 別名]
def __init__(self, gen, result_future, first_yielded):
self.gen = gen
self.result_future = result_future
self.future = _null_future
self.yield_point = None
self.pending_callbacks = None
self.results = None
self.running = False
self.finished = False
self.had_exception = False
self.io_loop = IOLoop.current()
# For efficiency, we do not create a stack context until we
# reach a YieldPoint (stack contexts are required for the historical
# semantics of YieldPoints, but not for Futures). When we have
# done so, this field will be set and must be called at the end
# of the coroutine.
self.stack_context_deactivate = None
if self.handle_yield(first_yielded):
self.run()
示例4: run_until_complete
# 需要導入模塊: import types [as 別名]
# 或者: from types import coroutine [as 別名]
def run_until_complete(self):
# Start all the coroutines.
for coro in self._new:
wait_for = coro.send(None)
heapq.heappush(self._waiting, Task(wait_for, coro))
# Keep running until there is no more work to do.
while self._waiting:
now = datetime.datetime.now()
# Get the coroutine with the soonest resumption time.
task = heapq.heappop(self._waiting)
if now < task.waiting_until:
# We're ahead of schedule; wait until it's time to resume.
delta = task.waiting_until - now
time.sleep(delta.total_seconds())
now = datetime.datetime.now()
try:
# It's time to resume the coroutine.
wait_until = task.coro.send(now)
heapq.heappush(self._waiting, Task(wait_until, task.coro))
except StopIteration:
# The coroutine is done.
pass
示例5: __init__
# 需要導入模塊: import types [as 別名]
# 或者: from types import coroutine [as 別名]
def __init__(self, gen, result_future, first_yielded):
self.gen = gen
self.result_future = result_future
self.future = _null_future
self.yield_point = None
self.pending_callbacks = None
self.results = None
self.running = False
self.finished = False
self.had_exception = False
self.io_loop = IOLoop.current()
# For efficiency, we do not create a stack context until we
# reach a YieldPoint (stack contexts are required for the historical
# semantics of YieldPoints, but not for Futures). When we have
# done so, this field will be set and must be called at the end
# of the coroutine.
self.stack_context_deactivate = None
if self.handle_yield(first_yielded):
gen = result_future = first_yielded = None
self.run()
示例6: test_func_4
# 需要導入模塊: import types [as 別名]
# 或者: from types import coroutine [as 別名]
def test_func_4(self):
async def foo():
raise StopIteration
check = lambda: self.assertRaisesRegex(
TypeError, "'coroutine' object is not iterable")
with check():
list(foo())
with check():
tuple(foo())
with check():
sum(foo())
with check():
iter(foo())
with silence_coro_gc(), check():
for i in foo():
pass
with silence_coro_gc(), check():
[i for i in foo()]
示例7: test_func_5
# 需要導入模塊: import types [as 別名]
# 或者: from types import coroutine [as 別名]
def test_func_5(self):
@types.coroutine
def bar():
yield 1
async def foo():
await bar()
check = lambda: self.assertRaisesRegex(
TypeError, "'coroutine' object is not iterable")
with check():
for el in foo(): pass
# the following should pass without an error
for el in bar():
self.assertEqual(el, 1)
self.assertEqual([el for el in bar()], [1])
self.assertEqual(tuple(bar()), (1,))
self.assertEqual(next(iter(bar())), 1)
示例8: test_set_wrapper_3
# 需要導入模塊: import types [as 別名]
# 或者: from types import coroutine [as 別名]
def test_set_wrapper_3(self):
async def foo():
return 'spam'
def wrapper(coro):
async def wrap(coro):
return await coro
return wrap(coro)
sys.set_coroutine_wrapper(wrapper)
try:
with silence_coro_gc(), self.assertRaisesRegex(
RuntimeError,
"coroutine wrapper.*\.wrapper at 0x.*attempted to "
"recursively wrap .* wrap .*"):
foo()
finally:
sys.set_coroutine_wrapper(None)
示例9: test_set_wrapper_4
# 需要導入模塊: import types [as 別名]
# 或者: from types import coroutine [as 別名]
def test_set_wrapper_4(self):
@types.coroutine
def foo():
return 'spam'
wrapped = None
def wrap(gen):
nonlocal wrapped
wrapped = gen
return gen
sys.set_coroutine_wrapper(wrap)
try:
foo()
self.assertIs(
wrapped, None,
"generator-based coroutine was wrapped via "
"sys.set_coroutine_wrapper")
finally:
sys.set_coroutine_wrapper(None)
示例10: test_non_gen_values
# 需要導入模塊: import types [as 別名]
# 或者: from types import coroutine [as 別名]
def test_non_gen_values(self):
@types.coroutine
def foo():
return 'spam'
self.assertEqual(foo(), 'spam')
class Awaitable:
def __await__(self):
return ()
aw = Awaitable()
@types.coroutine
def foo():
return aw
self.assertIs(aw, foo())
# decorate foo second time
foo = types.coroutine(foo)
self.assertIs(aw, foo())
示例11: test_async_def
# 需要導入模塊: import types [as 別名]
# 或者: from types import coroutine [as 別名]
def test_async_def(self):
# Test that types.coroutine passes 'async def' coroutines
# without modification
async def foo(): pass
foo_code = foo.__code__
foo_flags = foo.__code__.co_flags
decorated_foo = types.coroutine(foo)
self.assertIs(foo, decorated_foo)
self.assertEqual(foo.__code__.co_flags, foo_flags)
self.assertIs(decorated_foo.__code__, foo_code)
foo_coro = foo()
def bar(): return foo_coro
for _ in range(2):
bar = types.coroutine(bar)
coro = bar()
self.assertIs(foo_coro, coro)
self.assertEqual(coro.cr_code.co_flags, foo_flags)
coro.close()
示例12: test_returning_itercoro
# 需要導入模塊: import types [as 別名]
# 或者: from types import coroutine [as 別名]
def test_returning_itercoro(self):
@types.coroutine
def gen():
yield
gencoro = gen()
@types.coroutine
def foo():
return gencoro
self.assertIs(foo(), gencoro)
# decorate foo second time
foo = types.coroutine(foo)
self.assertIs(foo(), gencoro)
示例13: test_getcoroutinelocals
# 需要導入模塊: import types [as 別名]
# 或者: from types import coroutine [as 別名]
def test_getcoroutinelocals(self):
@types.coroutine
def gencoro():
yield
gencoro = gencoro()
async def func(a=None):
b = 'spam'
await gencoro
coro = func()
self.assertEqual(inspect.getcoroutinelocals(coro),
{'a': None, 'gencoro': gencoro})
coro.send(None)
self.assertEqual(inspect.getcoroutinelocals(coro),
{'a': None, 'gencoro': gencoro, 'b': 'spam'})
示例14: __init__
# 需要導入模塊: import types [as 別名]
# 或者: from types import coroutine [as 別名]
def __init__(self, coro, *, loop=None):
super().__init__(loop=loop)
if self._source_traceback:
del self._source_traceback[-1]
if not coroutines.iscoroutine(coro):
# raise after Future.__init__(), attrs are required for __del__
# prevent logging for pending task in __del__
self._log_destroy_pending = False
raise TypeError(f"a coroutine was expected, got {coro!r}")
self._must_cancel = False
self._fut_waiter = None
self._coro = coro
self._context = contextvars.copy_context()
self._loop.call_soon(self.__step, context=self._context)
_register_task(self)
示例15: get_stack
# 需要導入模塊: import types [as 別名]
# 或者: from types import coroutine [as 別名]
def get_stack(self, *, limit=None):
"""Return the list of stack frames for this task's coroutine.
If the coroutine is not done, this returns the stack where it is
suspended. If the coroutine has completed successfully or was
cancelled, this returns an empty list. If the coroutine was
terminated by an exception, this returns the list of traceback
frames.
The frames are always ordered from oldest to newest.
The optional limit gives the maximum number of frames to
return; by default all available frames are returned. Its
meaning differs depending on whether a stack or a traceback is
returned: the newest frames of a stack are returned, but the
oldest frames of a traceback are returned. (This matches the
behavior of the traceback module.)
For reasons beyond our control, only one stack frame is
returned for a suspended coroutine.
"""
return base_tasks._task_get_stack(self, limit)