Forwarding `return()` in generators

Axel Rauschmayer axel at rauschma.de
Thu Mar 26 21:50:46 UTC 2015


> We want `return` (Python 2.5+ close) to be optional, though. So an iterator whether implemented by a generator function or otherwise sees no difference -- provided in the generator function implementation you do not yield in a try with a finally. Forcing return from a not-exhausted generator parked at yield other than in try-with-finally does not run any more code in the generator function's body.

`return()` being optional is true for arrays:

```js
function twoLoops(iterable) {
    let iterator = iterable[Symbol.iterator]();
    for (let x of iterator) {
        console.log(x);
        break;
    }
    for (let x of iterator) {
        console.log(x);
        break;
    }
}

twoLoops(['a', 'b', 'c']);
// Output:
// a
// b
```

But it is not true for generators:

```js
function* elements() {
    yield 'a';
    yield 'b';
    yield 'c';
}

twoLoops(elements());
// Output:
// a
```

That is a difference between iterators that you have to be aware of and that needs to be documented per iterable. It’d be great if all iterables were indeed the same in this regard.

-- 
Dr. Axel Rauschmayer
axel at rauschma.de
rauschma.de



-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20150326/2e6a0de2/attachment-0001.html>


More information about the es-discuss mailing list