[Python-ideas] Yield-from: Nonexistent throw() and close()?

Jacob Holm jh at improva.dk
Sat Feb 21 09:26:44 CET 2009


Greg Ewing wrote:
> I'm happy to raise exceptions in the face of nonexistent
> send() methods, but I'm not so sure about throw() and
> close().
I'm not.  I'd hate for this:

def foo():
    for i in xrange(5):
        yield i

to behave different from this:

def foo():
    yield from xrange(5)

I think a missing send should be converted to a next, just as the PEP 
proposed.
>
> The purpose of close() is to make sure the generator is
> cleaned up before discarding it. If it's delegating to
> something that doesn't have a close(), then presumably
> that thing doesn't need to do any cleaning up, in which
> case we should just ignore it and close() the generator
> as usual.
>
> In the case of throw(), if we raise an AttributeError
> when the iterator doesn't have throw(), we're still
> going to end up raising an exception in the delegating
> generator, just not the one that was thrown in.
>
> One use case I can think of is for killing a generator-
> based thread -- you could define a KillThread exception
> for this and throw it into the thread you want to kill.
> The main loop of your scheduler would then catch
> KillThread exceptions and silently remove the thread
> from the system.
>
> But if the KillThread gets turned into something else,
> it won't get caught and everything will fall over for
> no good reason. So at least in that case I think it
> makes more sense to ignore the lack of a throw() method
> and raise the thrown-in exception in the delegating
> generator.
>
> Does this reasoning make sense?
>
Yup.  Works for me.

Regards

  Jacob




More information about the Python-ideas mailing list