I have a class Class
, that has a certain number of methods. I want to wrap each of those methods with a context manager, such that when calling Class().foo
, it will run Class.foo
in the context. Here's the code I have so far:
def wrap_all_methods_in_class_with_chdir_contextmanager(self):
@contextlib.contextmanager
def set_directory(path):
"""Sets the cwd within the context
Args:
path (Path): The path to the cwd
Yields:
None
"""
origin = os.path.abspath(os.getcwd())
try:
os.chdir(path)
yield
finally:
os.chdir(origin)
def wrapper(func):
def new_func(*args, **kwargs):
with set_directory(f"{ROOT}/{self.name}"):
getattr(self,func)(*args, **kwargs)
return new_func
for func in [func for func in dir(self) if callable(getattr(self, func)) and not func.startswith('__')]:
setattr(self,func,wrapper(getattr(self,func)))
I'm planning on calling this function (but defined before) at the end of a class definition, so after all the methods are defined