【发布时间】:2020-10-22 06:40:15
【问题描述】:
基本上我正在尝试在 Python 中使用异步代码。一开始,我想我会做一个斐波那契计算器。 但是我无法使用它,这是我的代码
import asyncio as a
cache = {}
async def fib(n):
if n < 10:
a.sleep(0.001)
else:
if n in cache:
result = cache[n]
else:
result = await fib(n - 2) + await fib(n - 1)
cache[n] = result
return result
async def main():
res = await fib(100)
print(res)
a.run(main())
我得到的错误是
Warning (from warnings module):
File "<pyshell#3>", line 4
RuntimeWarning: coroutine 'sleep' was never awaited
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
a.run(main())
File "C:\Users\Owner\AppData\Local\Programs\Python\Python38-32\lib\asyncio\runners.py", line 43, in run
return loop.run_until_complete(main)
File "C:\Users\Owner\AppData\Local\Programs\Python\Python38-32\lib\asyncio\base_events.py", line 616, in run_until_complete
return future.result()
File "<pyshell#5>", line 2, in main
res = await fib(100)
File "<pyshell#3>", line 9, in fib
result = await fib(n - 2) + await fib(n - 1)
File "<pyshell#3>", line 9, in fib
result = await fib(n - 2) + await fib(n - 1)
File "<pyshell#3>", line 9, in fib
result = await fib(n - 2) + await fib(n - 1)
[Previous line repeated 43 more times]
File "<pyshell#3>", line 11, in fib
return result
UnboundLocalError: local variable 'result' referenced before assignment
谢谢。
【问题讨论】:
-
await a.sleep(0) -
if n < 10"result" 未设置但已使用。 -
什么意思?我退货了。
-
您的代码实际上是同步的,因为您只使用事件循环安排一件事 (
main)。
标签: python python-3.x async-await python-asyncio