« Back to Index

Managing resources with Python Context Managers

View original Gist on GitHub

1. Context Manager - None.py

files = []

for _ in range(100000):
    f = open('foo.txt', 'w')
    f.close()
    files.append(f)

print(files)

2. Context Manager - Builtin.py

files = []

for _ in range(100000):
    with open('foo.txt', 'w') as f:
        files.append(f)

print(files)

3. Context Manager - Custom.py

files = []

class Open():
    def __init__(self, filename, mode):
        self.filename = filename
        self.mode = mode

    def __enter__(self):
        self.open_file = open(self.filename, self.mode)
        return self.open_file

    def __exit__(self, *args):
        self.open_file.close()

for _ in range(100000):
    with Open('foo.txt', 'w') as f:
        files.append(f)

print(files)

4. Context Manager - contextlib.py

from contextlib import contextmanager

files = []

@contextmanager
def open_file(path, mode):
    file = open(path, mode)
    yield file
    file.close()

for _ in range(100000):
    with open_file('foo.txt', 'w') as f:
        files.append(f)

print(files)