yieldPython中关键字的用途是什么?它有什么作用?
例如,我试图理解这段代码1:
def _get_child_candidates(self, distance, min_dist, max_dist):
if self._leftchild and distance - max_dist < self._median:
yield self._leftchild
if self._rightchild and distance + max_dist >= self._median:
yield self._rightchild
Run Code Online (Sandbox Code Playgroud)
这是来电者:
result, candidates = [], [self]
while candidates:
node = candidates.pop()
distance = node._get_dist(obj)
if distance <= max_dist and distance >= min_dist:
result.extend(node._values)
candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))
return result
Run Code Online (Sandbox Code Playgroud)
_get_child_candidates调用该方法时会发生什么?列表是否返回?单个元素?它又被召唤了吗?后续通话何时停止?
1.代码来自Jochen Schulz(jrschulz),他为度量空间创建了一个很棒的Python库.这是完整源代码的链接:模块mspace.
假设我有一个可以传递的异步迭代,async for然后如何将它映射并过滤到新的异步迭代器?以下代码是对我如何使用同步迭代执行相同操作的修改不起作用,因为s中yield不允许这样做async def.
async def mapfilter(aiterable, p, func):
async for payload in aiterable:
if p(payload):
# This part isn't allowed, but hopefully it should be clear
# what I'm trying to accomplish.
yield func(payload)
Run Code Online (Sandbox Code Playgroud) 我正在尝试将此Python2.7代码重写为新的异步世界顺序:
def get_api_results(func, iterable):
pool = multiprocessing.Pool(5)
for res in pool.map(func, iterable):
yield res
Run Code Online (Sandbox Code Playgroud)
map()阻塞直到计算完所有结果,所以我试图将其重写为异步实现,一旦准备就会产生结果.同样map(),返回值必须按照与之相同的顺序返回iterable.我试过这个(我需要requests因为传统的身份验证要求):
import requests
def get(i):
r = requests.get('https://example.com/api/items/%s' % i)
return i, r.json()
async def get_api_results():
loop = asyncio.get_event_loop()
futures = []
for n in range(1, 11):
futures.append(loop.run_in_executor(None, get, n))
async for f in futures:
k, v = await f
yield k, v
for r in get_api_results():
print(r)
Run Code Online (Sandbox Code Playgroud)
但是使用Python 3.6我得到了:
File "scratch.py", line 16, in <module>
for r in …Run Code Online (Sandbox Code Playgroud) 我有一个像这样的阻塞,非异步代码:
def f():
def inner():
while True:
yield read()
return inner()
Run Code Online (Sandbox Code Playgroud)
使用此代码,调用者可以选择何时停止函数以生成数据.如何将此更改为异步?此解决方案不起作用:
async def f():
async def inner():
while True:
yield await coroutine_read()
return inner()
Run Code Online (Sandbox Code Playgroud)
...因为 yield不能用于async def功能.如果我async从inner()签名中删除,我不能再使用await了.
我希望运行一个模拟,同时在一个 plot 中输出它的进度。我一直在查看很多线程和多处理的示例,但它们都非常复杂。所以我认为使用 Python 的新asyncio库应该会更容易。
我找到了一个例子(How to use 'yield' inside async function?)并为我的原因修改了它:
import matplotlib.pyplot as plt
import asyncio
import numpy as np
class DataAnalysis():
def __init__(self):
# asyncio so we can plot data and run simulation in parallel
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(self.plot_reward())
finally:
loop.run_until_complete(
loop.shutdown_asyncgens()) # see: https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.AbstractEventLoop.shutdown_asyncgens
loop.close()
async def async_generator(self):
for i in range(3):
await asyncio.sleep(.4)
yield i * i
async def plot_reward(self):
# Prepare the data
x = …Run Code Online (Sandbox Code Playgroud) 我正在尝试为websockets客户端学习异步。我尝试的每一段代码都会出现以下错误:
RuntimeError:无法从正在运行的事件循环中调用asyncio.run()
我尝试了最简单的代码,它始终会给出RuntimeError。我尝试再次安装完整的anaconda发行版,等等,但找不到问题所在。
我正在将Spyder 3.3.3与Python 3.7.3结合使用
可以正常工作的代码示例:
import asyncio
async def main():
print('hello')
await asyncio.sleep(1)
print('world')
asyncio.run(main())
Run Code Online (Sandbox Code Playgroud)
错误信息:
File "C:\Users\jmart\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 786, in runfile
execfile(filename, namespace)
File "C:\Users\jmart\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/jmart/Documents/asynk2.py", line 8, in <module>
asyncio.run(main())
File "C:\Users\jmart\Anaconda3\lib\asyncio\runners.py", line 34, in run
"asyncio.run() cannot be called from a running event loop")
RuntimeError: asyncio.run() cannot be called from a running event loop
Run Code Online (Sandbox Code Playgroud) python ×6
async-await ×2
asynchronous ×2
generator ×2
coroutine ×1
iterator ×1
matplotlib ×1
python-3.7 ×1
python-3.x ×1
yield ×1