Halil Yıldırım
Sep 24 · 2 min read
Photo by Tyler Daviaux on Unsplash

In this piece, we are going to delve into context managers in Python. I will keep it short — less talk, more work! I hope you enjoy it.


Why Context Managers?

Context managers are used to give resources back. Here’s what I mean:

f = open('file.txt', 'w')
f.write('Something to write')

We opened a file named file.txt and wrote it. Hang on — we didn’t close this file, so we can still use thef instance:

f = open('file.txt', 'w')
f.write('Something to write')
print('another work')
f.write('I can still write to file.txt')

This is a problem — resources are not unlimited so we have to give it back when we’re done with it. Here’s how we do it:

f = open('file.txt', 'w')
f.write('Something to write')
f.close()

With f.close() we closed the file.txt, so we can’t use this f any more:

f = open('file.txt', 'w')
f.write('Something to write')
f.close()
print(f.closed) # returns True

print(f.closed) will print True because f is closed, thanks to f.close().


How Do We Use Context Manager?

With a with statement. Let me give you an example:

with open('file.txt', 'w') as f:
f.write('Something to write')

But wait — where is the f.close()? Don’t worry, the with statement will take care of this and close the file:

with open('file.txt', 'w') as f:
f.write('Something to write')
print(f.closed)

See — I told you that print(f.closed) would print True!


Great! So, How Can I Write Mine?

Let me help you create your own. There are two ways to do it — I prefer to do it with class but I’ll show you both methods.

Method one

class OpenFile:
def __init__(self, file, mode):
self.file = file
self.mode = mode

def __enter__(self):
self.f = open(self.file, self.mode)
return self.f

def __exit__(self, exc_type, exc_val, exc_tb):
self.f.close()

Method two

from contextlib import contextmanager


@contextmanager
def OpenFile(file, mode):
f = open(file, mode)
yield f
f.close()

Try it out!

with OpenFile('file.txt', 'w') as f:
f.write('Something to write to mine')
print(f.closed)

More example: https://github.com/halilibrahim95/python-works

Better Programming

Advice for programmers.

Halil Yıldırım

Written by

Better Programming

Advice for programmers.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade