Special Method Protocols

__enter__() — context protocol

Enter a synchronous context manager. The value returned becomes the with-as target; it need not be self. If entry raises, the matching exit hook is not called.

Formal Syntax & Structure

python syntaxpython
def __enter__(self):

Return Value

object

Value bound by with-as.

Working Example

Example Snippetpython
class Session:    def __enter__(self): return "ready"    def __exit__(self, exc_type, exc, tb): return Falsedef demo():    with Session() as value: return valueprint(demo())
Python Reference