Skip to content

Instantly share code, notes, and snippets.

@heykarimoff
Created November 17, 2018 09:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heykarimoff/0728f108459c614fa5f42a6142e5ad3a to your computer and use it in GitHub Desktop.
Save heykarimoff/0728f108459c614fa5f42a6142e5ad3a to your computer and use it in GitHub Desktop.
Python context manager examples
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