Skip to content

Instantly share code, notes, and snippets.

@asnimansari
Created September 2, 2019 09:30
Show Gist options
  • Save asnimansari/4d2a6bafdb60824354939b5794764984 to your computer and use it in GitHub Desktop.
Save asnimansari/4d2a6bafdb60824354939b5794764984 to your computer and use it in GitHub Desktop.
Custom python context manager definition & its usage
# Context manager definition
class FileOpen(object):
def __init__(self, file_name, method):
self.file_object = open(file_name, method)
def __enter__(self):
return self.file_object
def __exit__(self, value, type, traceback):
self.file_object.close()
# Example usage
with FileOpen('discot.txt', 'w') as opened_file:
opened_file.write("I am a disco dancer")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment