« Return to Thread: try-except in generator methods

Re: try-except in generator methods

by Daniel Grunwald :: Rate this Message:

Reply to Author | View in Thread


Avish wrote:
> How do you know if the "enumeration was aborted"? The calling code
> gets back an IEnumerator and is free to call or not call MoveNext on
> it any number of times.
"for" should call enumerator.Dispose() just like "foreach" does in C#.

> Suppose I do this:
>
> def Generate():
>   try:
>     yield 42
>     yield 4242
>     yield 424242
>   ensure:
>     Dispose()
>
> def Consume():
>   for index, value in zip(range(2), Generate()):
>     print "${index} => ${value}"
>
> This will only consume only the first two yields (or even just the
> first one, I'm never sure about range()...). When, if at all, will the
> internal Dispose() code be called?
Compiling your code with my locally patched Boo version and then using
Reflector on it produces this:

public static void Consume()
{
    object[] enumerables = new object[] { Builtins.range(2), Generate() };
    IEnumerator ___iterator12 = Builtins.zip(enumerables);
    try
    {
        while (___iterator12.MoveNext())
        {
            object[] ___temp13 = (object[]) ___iterator12.Current;
            object index = ___temp13[0];
            object value = ___temp13[1];
            Builtins.print(new StringBuilder().Append(index).Append(" =>
").Append(value).ToString());
        }
    }
    finally
    {
        IDisposable ___disposable14 = ___iterator12 as IDisposable;
        if (___disposable14 != null)
        {
            ___disposable14.Dispose();
            // calls ZipEnumerator.Dispose, which in turn calls
Generate.$.Dispose, which then
            // a) does nothing if the iterator has been consumed
completely and thus already ran the ensure block
            // b) runs your ensure block (if the enumeration aborted
early), calling whatever Dispose() method you are referring to
        }
    }
}

I already got generating the correct code for the Generator.$.MoveNext()
and Generator.$.Dispose() methods nearly working.

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Boo Programming Language" group.
To post to this group, send email to boolang@...
To unsubscribe from this group, send email to boolang-unsubscribe@...
For more options, visit this group at http://groups.google.com/group/boolang
-~----------~----~----~----~------~----~------~--~---

 « Return to Thread: try-except in generator methods