Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

object.__enter__

The entry method runs before the with body and its result binds to the as target.

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

Syntax

with manager as value:
    use(value)

The entry method runs before the with body and its result binds to the as target.

object.__enter__

The result may be a resource distinct from the manager. If entry raises, neither the body nor this manager’s exit method runs.

After acquire the value is T7, its identity check against the manager is False, and release follows.

events=[]
class Broken:
    def __enter__(self): raise ValueError('acquire')
    def __exit__(self,*args): events.append('unexpected')
try:
    with Broken(): pass
except ValueError: pass
assert not events

Examples

class Ticket:
    def __enter__(self):
        print("acquire")
        return "T7"
    def __exit__(self, kind, error, trace):
        print("release")

manager = Ticket()
with manager as value:
    print(value, value is manager)

Result

acquire
T7 False
release

After acquire the value is T7, its identity check against the manager is False, and release follows.

Sources