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

contextlib.AbstractContextManager

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


Import

import contextlib
from contextlib import AbstractContextManager

Signature & Overview

contextlib.AbstractContextManager()

An abstract base class for context managers.

Usage

from contextlib import AbstractContextManager

class Resource(AbstractContextManager):
    def __init__(self) -> None:
        self.closed = False
    def __exit__(self, exc_type, exc, tb):
        self.closed = True
        return False

r = Resource()
with r as active:
    assert active is r and not r.closed
assert r.closed is True

Gotchas

REPL Inspect

from contextlib import AbstractContextManager
help(AbstractContextManager)

Linked from

Related notes