import contextlib
class MyWith:
def __enter__(self):
print('enter')
return self
def doThing(self):
print('do.....')
def __exit__(self, exc_type, exc_val, exc_tb):
print('exit')
with MyWith() as myw:
myw.doThing()
# enter
# do.....
# exit
@contextlib.contextmanager
def dowith(filename):
print('start')
yield {}
print('end')
with dowith('aa.txt') as dow:
print('do something....')
# start
# do something....
# end