Last active
November 26, 2020 17:37
-
-
Save StuffbyYuki/600dfdcf62aea3cad218ecb8742e5d17 to your computer and use it in GitHub Desktop.
Python: with statement --> context manager
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
# This trick is introduced in the book called Python Tricks | |
# When you do this | |
with open('hello.txt', 'w') as f: | |
f.write('hello, world!') | |
# You're essentially doing this | |
f = open('hello.txt', 'w') | |
try: | |
f.write('hello, world') | |
finally: | |
f.close() | |
# And you can define your own context manager with the help of __enter__ and __exit__ | |
class ManagedFile: | |
def __init__(self, name): | |
self.name = name | |
def __enter__(self): | |
self.file = open(self.name, 'w') | |
return self.file | |
def __exit__(self, exc_type, exc_val, exc_tb): | |
if self.file: | |
self.file.close() | |
with ManagedFile('hello.txt') as f: | |
f.write('hello, world!') | |
f.write('bye now') | |
# Or you can use the library for context manager | |
from contextlib import contextmanager | |
def managed_file(name): | |
try: | |
f = open(name, 'w') | |
yield f | |
finally: | |
f.close() | |
with managed_file('hello.txt') as f: | |
f.write('hello, world!') | |
f.write('bye now') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment