On this page
  1. contextlib.closing
  2. Import
  3. Signature & Overview
  4. Usage
  5. Gotchas
  6. REPL Inspect

contextlib.closing

Prev: contextlib.chdir | Up: contextlib | Next: contextlib.ContextDecorator
Rel: contextlib.AbstractAsyncContextManager, contextlib.AbstractContextManager, contextlib.aclosing, contextlib.asynccontextmanager
Ref: docs.python.org — contextlib.closing
Tags: #public #python3 #stdlib #contextlib


Import

import contextlib
from contextlib import closing

Signature & Overview

contextlib.closing(thing)

Context to automatically close something at the end of a block.

Usage

from contextlib import closing

class LegacyHandle:
    def __init__(self) -> None:
        self.closed = False
    def close(self) -> None:
        self.closed = True

h = LegacyHandle()
with closing(h) as active:
    assert active is h
assert h.closed is True

Gotchas

REPL Inspect

from contextlib import closing
help(closing)

Linked from

Related notes