Python 中的动态生成器

Dynamic Generator in Python

我需要创建一个可以管理动态资源的服务(我正在考虑一个正在增长的动态 csv。在这种情况下,我使用了一个列表来使它更容易理解),从返回下一个项目一个可迭代的。

如果列表完成,输出将为 False,我需要等待添加元素。

当最终添加元素时,生成器应该生成新添加的项目(这是我不明白该怎么做的部分)。

a_lst = [1, 2]


class DynamicGenerator:
    """
    Generic Generator that return item by item from a_lst and
    can append a new item when needed.
    """
    def __init__(self):
        global a_lst

    def gen_lst(self):
        for item in a_lst:
            yield item

    def grow_lst(self, new_item):
        a_lst.append(new_item)

class AvailableNextIterator:
    """
    Return next item from iterable if it's available,
    else return False.
    """
    def __init__(self, iterable):
        self.iterator = iterable

    def __next__(self):
        return next(self.iterator, False)


dg = DynamicGenerator()
gl = dg.gen_lst()

it = AvailableNextIterator(gl)

print(it.__next__())
print(it.__next__())
print(it.__next__())

dg.grow_lst(3)

print(it.__next__())

这是代码输出:

1
2
False
False

这是我需要的输出:

1
2
False
3

很简单,您在添加最后一项之前用尽了迭代;您已经触发了 gen_list 的数据结束异常。你已经退出了循环,并且没有重新进入的规定。您可以通过在该方法中进行一些简单的跟踪来看到这一点:

def gen_lst(self):
    for item in a_lst:
        yield item
    print("gen_lst is out of data")
    yield "over the cliff's edge ..."

现在,输出是

1
2
gen_lst is out of data
over the cliff's edge ...
False

你似乎想要一个FIFO队列;我建议您使用现成的包中可用的数据结构,而不是尝试自己动手。

但是,如果这是家庭作业:

  1. 按照 SO 发布标准的要求标记您的问题;
  2. 研究现有的实现。

将队列维护为实例的属性,而不是外部变量。您的“生成器”应该直接检查队列,而不是依赖 for 来管理迭代。