Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Context managers

A with statement binds the result of `__enter__` to its as target and invokes `__exit__` when leaving the block.

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

Syntax

with manager as resource:
    use(resource)

A with statement binds the result of __enter__ to its as target and invokes __exit__ when leaving the block.

After successful entry the exit method receives three None values on normal exit, or the exception type, value and traceback on failure. A truthy return suppresses the exception. If entry fails, this manager's exit is never called.

Stage returns ready and suppresses exactly ValueError, allowing continued to print.

calls=[]
class Context:
    def __init__(self,fail=False): self.fail=fail
    def __enter__(self):
        calls.append('enter')
        if self.fail: raise ValueError('entry')
        return self
    def __exit__(self,*exc): calls.append(exc[0]); return False
with Context(): pass
try:
    with Context(True): pass
except ValueError: pass
assert calls==['enter',None,'enter']

Examples

class Stage:
    def __enter__(self):
        return "ready"

    def __exit__(self, kind, value, trace):
        print("exit", kind.__name__ if kind else "ok")
        return kind is ValueError

with Stage() as state:
    print(state)
    raise ValueError("skip")
print("continued")

Result

ready
exit ValueError
continued

Stage returns ready and suppresses exactly ValueError, allowing continued to print.

Sources