avatarOliver S

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

2502

Abstract

text manager, <code>exit</code> upon leaving.</p><p id="9f52">For demonstration purposes, we create a naive context manager, purely to showcase its functionality:</p><div id="3537"><pre><span class="hljs-keyword">class</span> <span class="hljs-symbol">MyContextManager</span>(<span class="hljs-symbol">object</span>): <span class="hljs-symbol">def</span> <span class="hljs-symbol">init</span>(<span class="hljs-symbol">self</span>): <span class="hljs-symbol">print</span>("<span class="hljs-symbol">Init</span>")

<span class="hljs-symbol">def</span> <span class="hljs-symbol">__enter__</span>(<span class="hljs-symbol">self</span>):
    <span class="hljs-symbol">print</span>("<span class="hljs-symbol">Enter</span>")

<span class="hljs-symbol">def</span> <span class="hljs-symbol">__exit__</span>(<span class="hljs-symbol">self, <span class="hljs-symbol">type</span>, <span class="hljs-symbol">value</span>, <span class="hljs-symbol">traceback</span></span>):
    <span class="hljs-symbol">print</span>("<span class="hljs-symbol">Exit</span>")

<span class="hljs-symbol">with</span> <span class="hljs-symbol">MyContextManager</span>(): <span class="hljs-symbol">print</span>("<span class="hljs-symbol">Inside</span>")</pre></div><p id="e124">Running this code prints the following output:</p><p id="ffd1"><code>Init Enter Inside Exit</code></p><h1 id="b90e">Timed File Accessor</h1><p id="f5df">We finish this post with a somewhat more practical example, namely a context manager for accessing files — which automatically times how much time is spent with that file open:</p><div id="028a"><pre><span class="hljs-keyword">import</span> time

<span class="hljs-keyword">class</span> <span class="hljs-title class_">TimedFile</span>(<span class="hljs-title class_ inherited__">object</span>): <span class="hljs-keyword">def</span> <span class="hljs-title function_">init</span>(<span class="hljs-params">self, file_name, mode</span>): self.file = <span class="hljs-built_in">open</span>(file_name, mode) self.start_time = <span class="hljs-literal">None</span>

<span class="hljs-keyword">def</span> <span class="hljs-title function_">__enter__</span>(<span class="hljs-params">self</span>):
    self.start_time = time.time()
    <span class="hljs-keyword">return</span> self.file

<span class="hljs-keyword">def</span> <span class="hljs-title function_">__exit__</span>(<span class="hljs-params">self, <span class="hljs-bu

Options

ilt_in">type</span>, value, traceback</span>): self.file.close() <span class="hljs-built_in">print</span>(<span class="hljs-string">f"Time spent accessing file: <span class="hljs-subst">{time.time() - self.start_time}</span>s."</span>)

<span class="hljs-keyword">with</span> TimedFile(<span class="hljs-string">'demo.txt'</span>, <span class="hljs-string">'w'</span>) <span class="hljs-keyword">as</span> file: file.write(<span class="hljs-string">"test"</span>)</pre></div><p id="8537">Hope you liked this post, happy to have you back next time!</p><p id="96d5">This post is part of a series show-casing important Python concepts quickly. You can find the other parts here:</p><ul><li>Part 1: <a href="https://readmedium.com/lambda-functions-in-python-a124cebc2e99">Lambda Functions in Python</a></li><li>Part 2: <a href="https://readmedium.com/iterators-in-python-bd7332ddbc00">Iterators in Python</a></li><li>Part 3: <a href="https://readmedium.com/generators-and-generator-expressions-in-python-a8d2e700945e">Generators and Generator Expressions in Python</a></li><li>Part 4: <a href="https://readmedium.com/advanced-iteration-in-python-with-enumerate-and-zip-676b31ceac44">Advanced Iteration in Python with enumerate() and zip()</a></li><li>Part 6: <a href="https://readmedium.com/generating-temporary-files-and-directories-in-python-dfc11f017a97">Generating Temporary Files and Directories in Python</a></li><li>Part 7: <a href="https://readmedium.com/logging-in-python-3df84ce78cef">Logging in Python</a></li><li>Part 8: <a href="https://readmedium.com/partial-functions-in-python-66998eef1384">Partial Functions in Python</a></li><li>Part 9: <a href="https://readmedium.com/f-strings-in-python-80e30c64fb95">f-Strings in Python</a></li></ul><p id="ab65"><i>More content at <a href="https://plainenglish.io/"><b>PlainEnglish.io</b></a>.</i></p><p id="a233"><i>Sign up for our <a href="http://newsletter.plainenglish.io/"><b>free weekly newsletter</b></a>. Follow us on <a href="https://twitter.com/inPlainEngHQ"><b>Twitter</b></a></i>, <a href="https://www.linkedin.com/company/inplainenglish/"><b><i>LinkedIn</i></b></a><i>, <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><b>YouTube</b></a>, and <a href="https://discord.gg/GtDtUAvyhW"><b>Discord</b></a><b>.</b></i></p><p id="3c4b"><b><i>Interested in scaling your software startup</i></b><i>? Check out <a href="https://circuit.ooo?utm=publication-post-cta"><b>Circuit</b></a>.</i></p></article></body>

Managing Resources in Python with Context Managers (with statement)

Python Shorts — Part 5

Photo by Chris Ried on Unsplash

In this post we will have a look at context managers in Python. These are used via the with … statement, and work well e.g. for managing resources. In these use-cases, we want to acquire and make use of an resource, and eventually free it when finished — ideally without much code from the user. One prominent example is opening files — i.e. we want to open a file, read / write to it, and then close it again.

Introductory Example: File Access via Context Managers

The preferred Python way of doing this is as follows:

with open('file.txt', 'w') as file:
    file.write('test')

I have to admit, when starting with Python, I actually did not pay much attention to the inconspicuous expression with — coming from different languages, casually brushing it off as mere namespacing or similar.

However, above example actually uses a context manager. Whenever we use with, we do so. In this case, open returns a file object, which then in turn provides a context manager.

Defining Custom Context Managers

Now, let us dive deeper, understand what a context manager actually is and does, and how to generate our own.

In summary, a context manager is a class that implements the following functions: __init__, __enter__, and __exit__.

__init__ is the constructor, __enter__ is called when we “enter” the code block managed by the context manager, __exit__ upon leaving.

For demonstration purposes, we create a naive context manager, purely to showcase its functionality:

class MyContextManager(object):
    def __init__(self):
        print("Init")

    def __enter__(self):
        print("Enter")

    def __exit__(self, type, value, traceback):
        print("Exit")

with MyContextManager():
    print("Inside")

Running this code prints the following output:

Init Enter Inside Exit

Timed File Accessor

We finish this post with a somewhat more practical example, namely a context manager for accessing files — which automatically times how much time is spent with that file open:

import time

class TimedFile(object):
    def __init__(self, file_name, mode):
        self.file = open(file_name, mode)
        self.start_time = None

    def __enter__(self):
        self.start_time = time.time()
        return self.file

    def __exit__(self, type, value, traceback):
        self.file.close()
        print(f"Time spent accessing file: {time.time() - self.start_time}s.")

with TimedFile('demo.txt', 'w') as file:
    file.write("test")

Hope you liked this post, happy to have you back next time!

This post is part of a series show-casing important Python concepts quickly. You can find the other parts here:

More content at PlainEnglish.io.

Sign up for our free weekly newsletter. Follow us on Twitter, LinkedIn, YouTube, and Discord.

Interested in scaling your software startup? Check out Circuit.

Python
Context Managers
Python Programming
Recommended from ReadMedium