Created
March 30, 2024 22:24
-
-
Save normanlmfung/99a616ce412ffa1d28588663a139e659 to your computer and use it in GitHub Desktop.
python_syntax_contextlib
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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