Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save normanlmfung/99a616ce412ffa1d28588663a139e659 to your computer and use it in GitHub Desktop.
Save normanlmfung/99a616ce412ffa1d28588663a139e659 to your computer and use it in GitHub Desktop.
python_syntax_contextlib
# https://docs.python.org/3/library/contextlib.html
from contextlib import contextmanager
class MessageWriter(object):
def __init__(self, filename):
self.file_name = filename
@contextmanager
def open_file(self):
try:
file = open(self.file_name, 'w')
yield file # Note you're not returning here. You 'yield' instead.
finally:
file.close()
message_writer = MessageWriter('hello.txt')
with message_writer.open_file() as my_file:
my_file.write('hello world')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment