0

Python: Implement a custom context manager

 2 years ago
source link: https://proinsias.github.io/til/python-implement-a-custom-context-manager/
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

Francis T. O'Donovan

Senior Data Science Manager at Hospital IQ – Planet discoverer, researcher, developer, geek.

Python: Implement a custom context manager

less than 1 minute read

The context manager type is a Python feature to help work with unmanaged resources (e.g. file streams) which it is better to clean up or shutdown in an orderly manner after use, e.g. always closing a file after use).

The use of the with statement (on objects that support it, such as built-in or custom context managers) is used to ensure resources are cleaned up after use.

with can be seen as syntactic sugar for the try/except/finally block.

To implement a custom context manager, two methods must be implemented:

class my_context_manager:
  def __enter__(self):
      # set up things
      return thing
  def __exit__(self,type,value,traceback):
      # deal with unmanaged resources

with my_context_manager as custom_name
   # work with resources

When the with statement is executed, __enter__ is called, assigning the returned value to the variable after as.

Whatever happens in the code, the __exit__ method will be called in the end to make sure nothing is left unmanaged.

Via enkipro.com.

Tags: context python til

Categories: til

Updated: July 27, 2022

Previous Next

You May Also Enjoy


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK