Skip to content

Instantly share code, notes, and snippets.

@jsbueno
Last active July 12, 2019 14:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsbueno/53c059380be042e2878c08b5c10f36bf to your computer and use it in GitHub Desktop.
Save jsbueno/53c059380be042e2878c08b5c10f36bf to your computer and use it in GitHub Desktop.
Python recipe to enter an arbitrary number of contexts at once
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