Language improvement: Get more from the `for .. else` clause

Victor Savu victor.nicolae.savu at gmail.com
Wed Jun 29 07:11:20 EDT 2016


Sure.

Simple use-case: Decorate the yielded values and the return value of a
generator. Right now, with `yield from` you can only decorate the return
value, whereas with a for loop you can decorate the yielded values, but you
sacrifice the returned value altogether.

```
def ret_decorator(target_generator):
    returned_value = yield from target_generator()
    return decorate_ret(returned_value)

def yield_decorator(target_generator):
    for yielded_value in target_generator:
        yield decorate_yield(yielded_value)

    # Nothing to return. the target return value was
    # consumed by the for loop
```

With the proposed syntax, you can decorate both:

```
def decorator(target_generator):
    for yielded_value in target_generator:
        yield decorate_yield(yielded_value)
    else returned_value:
        return decorate_ret(returned_value)
```

Please let me know if you are interested in a more concrete case such as a
domain-specific application (I can think of progress bars, logging,
transfer rate statistics ...).

Best,
VS

On Mon, Jun 27, 2016 at 5:06 PM, Michael Selik <michael.selik at gmail.com>
wrote:

> On Mon, Jun 27, 2016 at 12:53 AM Victor Savu <
> victor.nicolae.savu at gmail.com> wrote:
>
>> capture the [StopIteration] value in the `else` statement of the `for`
>> loop
>>
>
> I'm having trouble thinking of a case when this new feature is necessary.
> Can you show a more realistic example?
>



More information about the Python-list mailing list