Last active
July 12, 2019 14:35
-
-
Save jsbueno/53c059380be042e2878c08b5c10f36bf to your computer and use it in GitHub Desktop.
Python recipe to enter an arbitrary number of contexts at once
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from contextlib import contextmanager | |
import sys | |
@contextmanager | |
def itercontext(*args): | |
contexts = [context.__enter__() for context in args] | |
try: | |
yield contexts | |
except BaseException as exc: | |
exc_type = type(exc) | |
exc_value = exc | |
traceback = exc.__traceback__ | |
else: | |
exc_type = exc_value = traceback = None | |
if exc_value and not all(context.__exit__(exc_type, exc_value, traceback) for context in args): | |
raise exc_value | |
def main(): | |
with itercontext(*(open(f"file_{i}.bin", "wb") for i in range(5))) as files: | |
for i, file_ in enumerate(files): | |
file_.write(bytes(i.to_bytes(1, "little"))) | |
if __name__ == "__main__": | |
main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment