Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

contextlib.AbstractContextManager

Supplies the context-manager entry protocol and returns the manager itself by default.

Version: Python 3.14; repository image, production runtime not attested

Syntax

class Scope(contextlib.AbstractContextManager): ...

Supplies the context-manager entry protocol and returns the manager itself by default.

The subclass must define exit behavior. Returning a truthy value there suppresses the exception raised in the body.

Use the abstract base for a synchronous with scope. Its concrete __enter__ returns the manager, while subclasses must define __exit__. Exit sees three None values on normal completion or the exception triple. The example accepts ValueError by returning True, so the next statement prints continued; other exceptions propagate.

from contextlib import AbstractContextManager
seen = []
class Scope(AbstractContextManager):
    def __exit__(self, typ, exc, tb):
        seen.append(typ)
        return typ is KeyError
s = Scope()
with s as obj:
    assert obj is s
with s:
    raise KeyError
assert seen == [None, KeyError]

Examples

import contextlib
class Scope(contextlib.AbstractContextManager):
    def __exit__(self, kind, value, tb):
        return kind is ValueError

scope = Scope()
with scope as obj:
    print(obj is scope)
    raise ValueError
print("continued")

Result

True
continued

Use the abstract base for a synchronous with scope. Its concrete `__enter__` returns the manager, while subclasses must define `__exit__`. Exit sees three None values on normal completion or the exception triple. The example accepts ValueError by returning True, so the next statement prints continued; other exceptions propagate.

Sources