Skip to content

Instantly share code, notes, and snippets.

@heykarimoff
Created November 17, 2018 09:58

Revisions

  1. heykarimoff created this gist Nov 17, 2018.
    34 changes: 34 additions & 0 deletions context_manager.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,34 @@
    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()