Baza znanjaIzpitno središče
SLSlovenščina
Izberi jezik13

CKTIS / Python

Upravljalniki konteksta

with veže rezultat `__enter__` na cilj za as in ob izhodu iz bloka pokliče `__exit__`.

Različica: Python 3.14; repository image, production runtime not attested

Sintaksa

with manager as resource:
    use(resource)

with veže rezultat __enter__ na cilj za as in ob izhodu iz bloka pokliče __exit__.

Po uspešnem vstopu izhod ob običajnem koncu prejme tri None, ob izjemi pa tip, vrednost in sled. Resnična vrnjena vrednost zatre izjemo. Ob neuspelem vstopu se izhod tega upravljalnika ne pokliče.

Stage vrne ready in zatre točno ValueError, zato se izpiše continued.

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']

Primeri

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")

Rezultat

ready
exit ValueError
continued

Stage vrne ready in zatre točno ValueError, zato se izpiše continued.

Viri