首页 > 解决方案 > 如果没有产生数据,则在生成器内引发错误

问题描述

yield如果没有发生,我想在生成器中引发错误。以下是我的问题的一个非常简化的示例:

def test1():
  for i in range(1, 28):
    if i % 5 == 0:
      yield str(i)
  raise CustomEXception

def test2(x):
  for i in range(1, 38):
    if i % x == 0:
      yield str(i)
  raise CustomEXception
   
a = test1()
b = test2()

和实际上是循环数据test1test2搜索匹配、操作数据和yield. 如果没有产生数据,则会引发错误。

for w,q in itertools.products(a, b):
   try:
     print(w + q)
     # do some more operation with w, q
   except CustomException:
     # do some more checking

生成器的结果用于创建笛卡尔积。

问题是这不起作用,引发了异常,之前没有任何结果。

标签: pythongenerator

解决方案


此外,您必须确保您的函数仅在raise没有异常的情况下才会出现yields

def test2(x):
    fail = True
    for i in range(1,38):
        if i % x == 0:
            fail = False  
            yield str(i)
    if fail:
        raise ValueError

这样,如果有一个或多个,yields则不会引发异常product并将生成自己的生成器。


推荐阅读