Fail to get node while awaiting an async function
Source file:
import asyncio
import inspect
import executing
def test1():
frame = inspect.currentframe()
assert frame is not None
call_frame = frame.f_back
assert call_frame is not None
declare_frame = call_frame.f_back
assert declare_frame is not None
node = executing.Source.executing(declare_frame).node
assert node is not None # Fail, why the node is None?
async def test():
test1()
async def test2():
await test()
asyncio.run(test2())
And the typing of .node is EnhancedAST without Optional, which also problems.
Executing:
PS D:\projects\physicsLab> & D:/projects/physicsLab/venv/Scripts/python.exe d:/projects/physicsLab/myTest5.test.py
Traceback (most recent call last):
File "d:\projects\physicsLab\myTest5.test.py", line 21, in <module>
asyncio.run(test2())
~~~~~~~~~~~^^^^^^^^^
File "D:\toolchains\python313\Lib\asyncio\runners.py", line 194, in run
return runner.run(main)
~~~~~~~~~~^^^^^^
File "D:\toolchains\python313\Lib\asyncio\runners.py", line 118, in run
return self._loop.run_until_complete(task)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^
File "D:\toolchains\python313\Lib\asyncio\base_events.py", line 720, in run_until_complete
return future.result()
~~~~~~~~~~~~~^^
File "d:\projects\physicsLab\myTest5.test.py", line 19, in test2
await test()
File "d:\projects\physicsLab\myTest5.test.py", line 16, in test
test1()
~~~~~^^
File "d:\projects\physicsLab\myTest5.test.py", line 13, in test1
assert node is not None
^^^^^^^^^^^^^^^^
AssertionError
PS D:\projects\physicsLab>
Environment:
- OS: Windows11 (22h4)
- Python: CPython 3.13
And the typing of .node is EnhancedAST without Optional, which also problems.
I agree that the typing is bad in general.
Why does it fail to get the node? Because await is weird and magical. Look at the traceback. Every other frame has ~ and ^ markers. Even Python itself fails to identify the node. And if you repeatedly print frame.f_back you'll see it prints something different from the traceback, another hint at the weirdness.
It might be possible, maybe using the older SentinelNodeFinder and looking for await nodes when finding the SEND instruction. But in general, you should expect .node to be None sometimes.