Context Manager in Python

Introduction

A context manager is an object that can be used in a code block with to wrap code between the entry and exit actions.

The entry action is defined in the method __enter__(), the exit one in the method __exit__()

__exit__() must accept three positional arguments that contain information about exceptions:

the exception type, value and traceback.

You can study an example with their use here

Official documentation:

context-managers , with

Perhaps the most popular example of use is with open() for opening files .

Example

class Example: def __enter__(self): print("enter") def __exit__(self, exc_type, exc_val, exc_tb): print("exit") with Example(): print("Yay Python!")

enter Yay Python! exit

A more practical example - the context manager will temporarily change an environment variable.

import os class set_env_var: def __init__(self, var_name, new_value): self.var_name = var_name self.new_value = new_value def __enter__(self): self.original_value = os.environ.get(self.var_name) os.environ[self.var_name] = self.new_value def __exit__(self, exc_type, exc_val, exc_tb): if self.original_value is None: del os.environ[self.var_name] else: os.environ[self.var_name] = self.original_value print("USERNAME env var is", os.environ["USERNAME"]) with set_env_var("USERNAME", "DEVHOPS-RU"): print("USERNAME env var is", os.environ["USERNAME"]) print("USERNAME env var is", os.environ["USERNAME"])

USERNAME env var is ANDREI USERNAME env var is DEVHOPS-RU USERNAME env var is ANDREI

as

With as you can define a variable that will point to what __enter__() returns.

If __enter__() returns nothing, as in the previous example, then the variable will be None.

with set_env_var("USERNAME", "TESTSETUP-RU") as result: print("USERNAME env var is", os.environ["USERNAME"]) print("Result from __enter__ method:", result)

USERNAME env var is TESTSETUP-RU Result from __enter__ method: None

import time class Timer: def __enter__(self): self.start = time.perf_counter() return self def __exit__(self, exc_type, exc_val, exc_tb): self.stop = time.perf_counter() self.elapsed = self.stop - self.start t = Timer() with t: time.sleep(.5) print(t.elapsed) with Timer() as t: time.sleep(1) print(t.elapsed)

0.5005884999991395 1.0005807999987155

Own version of open

class File(object): def __init__(self, file_name, method): self.file_obj = open(file_name, method) def __enter__(self): return self.file_obj def __exit__(self, exc_type, exc_value, exc_traceback): self.file_obj.close() with File('sites.md', 'w') as f: f.write('www.devhops.ru')

If there are no errors, the process is as follows

  1. The with statement stores the __exit__ method of the File class.
  2. It calls the __enter__ method of the File class.
  3. The __enter__ method opens the file and returns it.
  4. The opened file handle is passed to f.
  5. We write to the file using .write().
  6. The with statement calls the stored __exit__ method.
  7. The __exit__ method closes the file.

Error Handling

If in the example with our own version of open we call, instead of write() a non-existent method, an exception will appear.

with File('sites.md', 'w') as f: f.undefined('www.devhops.ru')

Traceback (most recent call last): File "C:\Users\Andrei\context.py", line 11, in <module> f.undefined('www.devhops.ru') ^^^^^^^^^^^ AttributeError: '_io.TextIOWrapper' object has no attribute 'undefined'

You can handle it in the method __exit__()

class File(object): def __init__(self, file_name, method): self.file_obj = open(file_name, method) def __enter__(self): return self.file_obj def __exit__(self, exc_type, exc_value, exc_traceback): if exc_type is not None: print("Exception has been handled") print("Exception type is", exc_type) print("Exception value is", exc_value) print("Exception traceback is", exc_traceback) if exc_type is AttributeError: print("AttributeError") self.file_obj.close() return True with File('sites.md', 'w') as f: f.unknown('www.devhops.ru')

Exception has been handled Exception type is <class 'AttributeError'> Exception value is '_io.TextIOWrapper' object has no attribute 'undefined' Exception traceback is <traceback object at 0x0000016845C87D40> AttributeError

Nothing will be written to the file.

If you want the undefined method to work like write you need to set this in __init__()

class File(object): def __init__(self, file_name, method): self.file_obj = open(file_name, method) self.file_obj.undefined = self.file_obj.write … with File('sites.md', 'w') as f: f.undefined('www.devhops.ru')

cat sites.md

www.devhops.ru

Article author: Andrei Olegovich