Python Context Manager: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 17: Line 17:
finally:
finally:
   r.close()
   r.close()
</syntaxhighlight>
The equivalent semantics using a context manager can be achieved with this syntax:
<syntaxhighlight lang='py'>
with <create-context> as ctx:
  #
  # use the context
  #
#
# at the exit from the indented block, the context is automatically cleaned up
#
</syntaxhighlight>
</syntaxhighlight>

Revision as of 00:19, 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
#