[ Python ]如何取回生成器的返回值

2021-09-20 23:11:16 +08:00
 MiketsuSmasher

以下是一个校验文件的函数,algorithm_name是哈希类型的名称,checksum是已知的校验码。

def iter_check(filepath: str | bytes | os.PathLike[str | bytes], algorithm_name: str, checksum: str):
    algorithm = get_algorithm(algorithm_name)
    with open(filepath, mode='rb') as file:
        algorithm_instance = algorithm()
        for block in iter(partial(file.read, 1024), b''):
            yield block
            algorithm_instance.update(block)
    return algorithm_instance.hexdigest() == checksum

其本质上是一个生成器,每一次迭代都会yield一个block。那么,能否取回最后由return返回的校验结果?

2057 次点击
所在节点    Python
3 条回复
chenstack
2021-09-21 00:58:04 +08:00
生成器迭代结束后会生成一个 StopIteration,返回值就是这个 StopIteration 的 value
def iter_check():
    for i in range(5):
        yield i
    return 10


checker = iter_check()
while True:
    try:
        print(next(checker))
    except StopIteration as e:
        print("result: ", e.value)
        break
BBCCBB
2021-09-21 09:41:01 +08:00
for 循环, 或者看一下 next 函数的用法.
O5oz6z3
2021-09-25 06:53:40 +08:00
基本原理已经被楼上说完了,至于你的需求可以很容易想到一个简单的实现,不知道有没有现成的:
class wrapiter:
... def __init__(self, _iter):
... ... self.iter = iter(_iter)
... ... self.val = None
... def __iter__(self):
... ... return self
... def __next__(self):
... ... try:
... ... ... return next(self.iter)
... ... except StopIteration as e:
... ... ... self.val = e.value
... ... ... raise

it = wrapiter(range(9))
print([x for x in it])
print(it.val)

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/803110

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX