Looping over resource in python
-
07-07-2021 - |
문제
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.)
해결책
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.
다른 팁
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...
제휴하지 않습니다 StackOverflow