Created
November 17, 2018 09:58
-
-
Save heykarimoff/0728f108459c614fa5f42a6142e5ad3a to your computer and use it in GitHub Desktop.
Python context manager examples
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
import json | |
from contextlib import contextmanager | |
data = {'key': 1234} | |
with open('the_json_file.json', 'wt') as json_file: | |
json.dump(data, json_file) | |
with OpenFile('the_json_file.json', 'wt') as json_file: | |
json.dump(data, json_file) | |
with open_file('the_json_file.json', 'wt') as json_file: | |
json.dump(data, json_file) | |
# Version 1 | |
class OpenFile: | |
def __init__(self, filename, mode): | |
self.filename = filename | |
self.mode = mode | |
def __enter__(self): | |
self.file = open(self.filename, self.mode) | |
return self.file | |
def __exit__(self): | |
self.file.close() | |
# Version 2 | |
@contextmanager | |
def open_file(filename, mode): | |
file = open(filename, mode) | |
yield file | |
file.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment