Frage

Is there a shorter way to do the following for-with combination:

for resource in gen_resources():
    with resource:
        DoWork1(resource)
        .
        .
        DoWorkN(resource)

If possible, I'd like to avoid the extra line + indentation.

Resource could be anything that has to be finalized upon leaving the loop iteration (open file, active object, etc.)

War es hilfreich?

Lösung

You can create a generator function that performs the with statement on each element:

def iterate_with(iterable):
    for element in iterable:
        with element:
            yield element

Use:

for resource in iterate_with(gen_resources()):
    DoWork(resource)

I'd probably still use your original code over this, since it may not be clear to the reader of the code that the with statement is used here.

Andere Tipps

Only because you have one statement inside the with:

for resource in gen_resources():
    with resource:  DoWork(resource)

This seems to be generally frowned upon, but I have no idea why - for and if can do the same thing, and it's pretty convenient...

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top