4

reachtim

 3 years ago
source link: https://reachtim.com/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

The contextmanager Decorator

Wed 22 January 2020

Table of Contents

Overview

Generally, you create a context manager by creating a class with __enter__ and __exit__ methods, but this example shows you how to use the @contextlib.contextmanager to create a simple context manager.

Context managers provide a cool programming pattern, especially if you’re forgetful or just have too much to keep track of and you want to simplify your life.

You’ll find them helpful when you have opened something and need to close it, locked something and need to release it, or changed something and need to reset it. There are several built in context managers that you’re probably familiar with like open to open a file or socket to use a socket. The bog-standard example:

with open('myfile.txt') as f:
    lines = f.readlines()

do_stuff(lines)

The open context manager opens a file, returns an object we name as f. When we’ve done all the things we’re going to with it, (we fall out of the with statement block), the file is automatically closed for us.

In this brief article, you’ll see how you can create a dead-simple context manager from a generator.

Let’s Code

Create the Context Manager

First import the contextlib module. It has several helpers (read more here: contextlib module).

We’re just going to decorate the chdir function as a contextlib.contextmanager.

import contextlib

@contextlib.contextmanager
def chdir(path):
    """
    On enter, change directory to specified path.
    On exit, change directory to original.
    """
    this_dir = os.getcwd()
    os.chdir(path)
    try:
        yield
    finally:
        os.chdir(this_dir)

To make this work, the function must be a generator and yield exactly once. At the point of the yield, the calling process is executed.

In chdir, the function takes a single argument, path.

  1. First it makes a note of the current directory and then changes to the path.
  2. Then it yields control back to the caller.
  3. No matter what happens during that process, the function will finally change back to the original directory.

Use the Context Manager

Suppose you have some function gather_paths you want to call for a set of directories. The following example shows how the chdir context manager could be used:

with chdir("/mydownloads/wordpress"):
    gather_paths()

I like this little context manager; it keeps me from having to remember to switch back to the original directory so I don’t get surprised later and find my program is executing somewhere else.

As long as I call the function as a context manager using the with statement, I don’t have to remember to change back to the original directory or do anything special.

Category: Python

Tagged: Python hacking

comments


Reading Binary Data with Python

Mon 20 January 2020

Two ways to read binary data into a Python data structure.

Category: Python

Tagged: Python hacking

comments

Read More

Include HTML in LaTeX

Mon 06 May 2019

How to include HTML content in your LaTeX documents.

Category: LaTeX

Tagged: how-to

comments

Read More

DIY System Monitoring, Part 3: Visualization

Mon 29 April 2019

How to use Python3, psutil, and MongoDB with NodeJS/Javascript for monitoring system health.

Category: Javascript

Tagged: sysadmin how-to web

comments

Read More

DIY System Monitoring, Part 2

Mon 22 April 2019

How to use Python3, psutil, and MongoDB with NodeJS/Javascript for monitoring system health.

Category: NodeJS

Tagged: sysadmin how-to web

comments

Read More

DIY System Monitoring, Part 1: Python

Tue 16 April 2019

How to use Python3, psutil, and MongoDB with Javascript for monitoring system health.

Category: Python

Tagged: sysadmin how-to web

comments

Read More

Testing PDFs with Python

Mon 26 January 2015

Methods for testing PDFs using Python

Category: Python

Tagged: how-to pdf

comments

Read More

Manipulate PDFs with Python

Mon 12 January 2015

Methods for manipulating and extracting information from PDF documents using Python

Category: Python

Tagged: how-to pdf

comments

Read More

SAS and LaTeX Together: The StatRep Package

Sun 23 November 2014

How to use StatRep with SAS-generated LaTeX output for reproducible research.

Category: LaTeX

Tagged: how-to statrep

comments

Read More

Create Keywords Metadata From Index Terms

Fri 03 October 2014

How to harvest index terms in DocBook XML to create keywords for HTML.

Category: XML

Tagged: how-to docbook xslt

comments

Read More

BAM! A Web Framework “Short Stack”

Mon 29 September 2014

Use BAM (Bottle, Apache, and MongoDB) to create a quick website.

Category: Python

Tagged: how-to web

comments

Read More

How To Pad a PDF to an N Page Signature

Sat 13 September 2014

How to use LaTeX to force a PDF to have a multiple of n pages.

Category: LaTeX

Tagged: how-to

comments

Read More

psutil and MongoDB for System Monitoring

Wed 03 September 2014

How to use psutil and MongoDB for monitoring system health.

Category: Python

Tagged: sysadmin how-to web

comments

Read More

Pelican Configuration for ReachTim.com

Wed 20 August 2014

How this site is set up

Category: Python

Tagged: python web

comments

Read More

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK