Skip to content

Commit

Permalink
Add MultiContextManager class to enable multiple context managers at …
Browse files Browse the repository at this point in the history
…once
  • Loading branch information
RichieHakim committed Mar 30, 2024
1 parent 000e158 commit 4f6ee7c
Showing 1 changed file with 32 additions and 1 deletion.
33 changes: 32 additions & 1 deletion bnpm/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from pathlib import Path
import warnings
from typing import Callable, List, Any, Dict
from contextlib import contextmanager
from contextlib import contextmanager, ExitStack


def estimate_array_size(
Expand Down Expand Up @@ -463,6 +463,37 @@ def wrapped(*args, **kwargs):
return wrapper


class MultiContextManager:
"""
A context manager that allows multiple context managers to be used at once.
RH 2024
Args:
*managers (context managers):
Multiple context managers to be used at once.
Demo:
.. code-block:: python
with MultiContextManager(
torch.no_grad(),
temp_set_attr(obj, attr, new_val),
open('file.txt', 'w') as f,
):
# do something
"""
def __init__(self, *managers):
self.managers = managers
self.stack = ExitStack()

def __enter__(self):
for manager in self.managers:
self.stack.enter_context(manager)

def __exit__(self, exc_type, exc_value, traceback):
self.stack.__exit__(exc_type, exc_value, traceback)


#########################################################
############ INTRA-MODULE HELPER FUNCTIONS ##############
#########################################################
Expand Down

0 comments on commit 4f6ee7c

Please sign in to comment.