What is generator.throw() good for?

后端 未结 4 1649
被撕碎了的回忆
被撕碎了的回忆 2021-01-30 19:55

PEP 342 (Coroutines via Enhanced Generators) added a throw() method to generator objects, which allows the caller to raise an exception inside the generato

4条回答
  •  你的背包
    2021-01-30 20:43

    One use case is to include information about the internal state of a generator in the stack trace when an exception occurs -- information that would not otherwise be visible to the caller.

    For example, say we have a generator like the following where the internal state we want is the current index number of the generator:

    def gen_items():
        for i, item in enumerate(["", "foo", "", "foo", "bad"]):
            if not item:
                continue
            try:
                yield item
            except Exception:
                raise Exception("error during index: %d" % i)
    

    The following code is not sufficient to trigger the additional exception handling:

    # Stack trace includes only: "ValueError: bad value"
    for item in gen_items():
        if item == "bad":
            raise ValueError("bad value")
    

    However, the following code does provide the internal state:

    # Stack trace also includes: "Exception: error during index: 4"
    gen = item_generator()
    for item in gen:
        if item == "bad":
            gen.throw(ValueError, "bad value")
    

提交回复
热议问题