from contextlib import contextmanager
class Test(object):
pass
ctx = Test()
@contextmanager
def do_with_log(log_file_path):
try:
ctx.log = open(log_file_path, 'w')
yield ctx.log
except Exception:
pass
finally:
ctx.log.close()
ctx.log = None
with do_with_log('test.txt') as log:
log.write('123')
print getattr(ctx, 'log', None)
print getattr(ctx, 'log', None)