我的代码中有一个具有属性的类,偶尔需要运行异步代码。有时我需要从异步函数访问该属性,有时需要从同步函数访问-这就是为什么我不希望我的属性是异步的原因。此外,我认为异步属性通常是一种代码异味,请纠正我如果我错了。
我在执行同步属性中的异步方法并阻止进一步执行直到异步方法完成方面存在问题。
以下是示例代码:
import asyncio
async def main():
print('entering main')
synchronous_property()
print('exiting main')
def synchronous_property():
print('entering synchronous_property')
loop = asyncio.get_event_loop()
try:
# this will raise an exception, so I catch it and ignore
loop.run_until_complete(asynchronous())
except RuntimeError:
pass
print('exiting synchronous_property')
async def asynchronous():
print('entering asynchronous')
print('exiting asynchronous')
asyncio.run(main())
它的输出:
entering main
entering synchronous_property
exiting synchronous_property
exiting main
entering asynchronous
exiting asynchronous
首先,捕获RuntimeError
似乎是错误的,但如果我不这样做,就会出现RuntimeError: This event loop is already running
异常。
其次,asynchronous()
函数在同步函数执行完成后才被执行。我想对异步方法处理的数据进行一些处理,因此需要等待它完成。如果在调用synchronous_property()
之后添加await asyncio.sleep(0)
,它将在main()
完成之前调用asynchronous()
,但这对我没有帮助。我需要在synchronous_property()
完成之前运行asynchronous()
。
我错了什么?我正在运行python 3.7。