Is there a Pythonic way to automatically __exit__
all members of a class?
class C:
def __init__(self):
self.a = open('foo')
self.b = open('bar')
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
# Is it correct to just forward the parameters here?
self.a.__exit__(self, exc_type, exc_value, traceback)
self.b.__exit__(self, exc_type, exc_value, traceback)
Can I do this without manually calling __exit__
on a
and b
? Am I even calling __exit__
correctly?
Suppose that the resources I have aren't file
s like in the example and there isn't a method like close
or destroy
. Is it perhaps good practice to implement a method like this on top of the __enter__
and __exit__
?