Python Context Manager: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 34: Line 34:
=How it Works=
=How it Works=


When the interpreter encounters the <code>[[Python_Language#with|with]]</code> statement, it creates a new context.
When the interpreter encounters the <code>[[Python_Language#with|with]]</code> statement, it executes whatever follows <code>with</code>, expecting that the result of the execution is a context manager object: an object that implements the [[#The_Context_Manager_Protocol]] protocol.
 
The interpreter continues by invoking the <code>__enter__()</code> on the context manager instance. The <code>__enter__()</code> method may optionally return an object instance, which is assigned to the variable name following the <code>as</code> reserved keyword. The instance is accessible from the indented block that follows <code>with</code>.


The context an optionally return an object, which is accessible from the indented block that follows <code>with</code>.
=Context Manager Protocol=
=Context Manager Protocol=

Revision as of 00:41, 29 August 2022

External

Internal

Overview

An execution context is useful when the code uses resources that need closing, even if the code follows an unexpected execution path, like when an exception is raised.

An execution context is equivalent with the following construct:

r = Resource()
r.open()
try:
  #
  # use resource, while anywhere in this code block exception might be thrown
  #
finally:
  r.close()

The equivalent semantics using a context manager can be achieved with this syntax:

with <create-context> as ctx:
  #
  # use the context
  #

#
# at the exit from the indented block, the context is automatically cleaned up
#

How it Works

When the interpreter encounters the with statement, it executes whatever follows with, expecting that the result of the execution is a context manager object: an object that implements the #The_Context_Manager_Protocol protocol.

The interpreter continues by invoking the __enter__() on the context manager instance. The __enter__() method may optionally return an object instance, which is assigned to the variable name following the as reserved keyword. The instance is accessible from the indented block that follows with.

Context Manager Protocol