Sobes.tech
Junior — Middle

What keyword in Python is used to define a context manager?

sobes.tech AI

Answer from AI

In Python, the with keyword is used to define a context manager, and to create a custom context manager, the methods __enter__ and __exit__ are typically used in a class.

However, if it is about declaring a function-based context manager, the @contextmanager decorator from the contextlib module is used.

Example of creating a context manager with a class:

class MyContextManager:
    def __enter__(self):
        print('Entering context')
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('Exiting context')

with MyContextManager():
    print('Inside context')

Example using @contextmanager:

from contextlib import contextmanager

@contextmanager
def my_context():
    print('Entering')
    yield
    print('Exiting')

with my_context():
    print('Inside')

Thus, the key words for working with a context manager are with (for usage) and the methods __enter__ and __exit__ (for definition).

What keyword in Python is used to define a context… - sobes.tech