ID EN
Contextlib

ContextDecorator

Python 3.11 🇮🇩 Bahasa Indonesia

Kelas dasar yang memungkinkan pengelola konteks juga digunakan sebagai dekorator.

Syntax

PYTHON
class contextlib.ContextDecorator

Contoh

Example 1
PYTHON
from contextlib import ContextDecorator

class mycontext(ContextDecorator):
    def __enter__(self):
        print('Starting')
        return self

    def __exit__(self, *exc):
        print('Finishing')
        return False
Example 2
PYTHON
>>> @mycontext()
... def function():
...     print('The bit in the middle')
...
>>> function()
Starting
The bit in the middle
Finishing

>>> with mycontext():
...     print('The bit in the middle')
...
Starting
The bit in the middle
Finishing
Example 3
PYTHON
def f():
    with cm():
         Do stuff
Example 4
PYTHON
@cm()
def f():
     Do stuff
Example 5
PYTHON
from contextlib import ContextDecorator

class mycontext(ContextBaseClass, ContextDecorator):
    def __enter__(self):
        return self

    def __exit__(self, *exc):
        return False

See Also

contextmanager() with