Python Glossary Русский

all Python 3OOPfunction

__enter__

context manager

The method run on entering a with block. Whatever it returns is bound to the name after as.

Syntax

def __enter__(self): ...

__enter__ usually returns self but does not have to: open() returns the file itself, while a lock manager may return nothing. If __enter__ raises, the with body never runs and __exit__ is not called — anything acquired before the error must be released inside __enter__ itself.

Examples

class Connection:
    def __enter__(self):
        print('connect')
        return 'conn#1'
    def __exit__(self, *exc):
        print('close')
with Connection() as c:
    print(c)  # → connect / conn#1 / close

See also

Open in the full glossarydocs.python.orgReport an inaccuracy