MCPcopy Index your code
hub / github.com/python/cpython / test_compile_top_level_await

Method test_compile_top_level_await

Lib/test/test_builtin.py:477–559  ·  view source on GitHub ↗

Test whether code with top level await can be compiled. Make sure it compiles only with the PyCF_ALLOW_TOP_LEVEL_AWAIT flag set, and make sure the generated code object has the CO_COROUTINE flag set in order to execute it with `await eval(.....)` instead of exec, or

(self)

Source from the content-addressed store, hash-verified

475
476
477 def test_compile_top_level_await(self):
478 """Test whether code with top level await can be compiled.
479
480 Make sure it compiles only with the PyCF_ALLOW_TOP_LEVEL_AWAIT flag
481 set, and make sure the generated code object has the CO_COROUTINE flag
482 set in order to execute it with `await eval(.....)` instead of exec,
483 or via a FunctionType.
484 """
485
486 # helper function just to check we can run top=level async-for
487 async def arange(n):
488 for i in range(n):
489 yield i
490
491 class Lock:
492 async def __aenter__(self):
493 return self
494
495 async def __aexit__(self, *exc_info):
496 pass
497
498 async def sleep(delay, result=None):
499 assert delay == 0
500 await async_yield(None)
501 return result
502
503 modes = ('single', 'exec')
504 optimizations = (-1, 0, 1, 2)
505 code_samples = [
506 '''a = await sleep(0, result=1)''',
507 '''async for i in arange(1):
508 a = 1''',
509 '''async with Lock() as l:
510 a = 1''',
511 '''a = [x async for x in arange(2)][1]''',
512 '''a = 1 in {x async for x in arange(2)}''',
513 '''a = {x:1 async for x in arange(1)}[0]''',
514 '''a = [x async for x in arange(2) async for x in arange(2)][1]''',
515 '''a = [x async for x in (x async for x in arange(5))][1]''',
516 '''a, = [1 for x in {x async for x in arange(1)}]''',
517 '''a = [await sleep(0, x) async for x in arange(2)][1]''',
518 # gh-121637: Make sure we correctly handle the case where the
519 # async code is optimized away
520 '''assert not await sleep(0); a = 1''',
521 '''assert [x async for x in arange(1)]; a = 1''',
522 '''assert {x async for x in arange(1)}; a = 1''',
523 '''assert {x: x async for x in arange(1)}; a = 1''',
524 '''
525 if (a := 1) and __debug__:
526 async with Lock() as l:
527 pass
528 ''',
529 '''
530 if (a := 1) and __debug__:
531 async for x in arange(2):
532 pass
533 ''',
534 ]

Callers

nothing calls this directly

Calls 6

dedentFunction · 0.90
run_yielding_async_fnFunction · 0.90
compileFunction · 0.50
subTestMethod · 0.45
assertRaisesMethod · 0.45
assertEqualMethod · 0.45

Tested by

no test coverage detected