Use the same function as context manager and decorator
Posted on 2022-09-25 in Trucs et astuces • Tagged with Python
I recently learned that context managers created with @contextmanager can be used either as a context manager or a decorator:
from contextlib import contextmanager @contextmanager def test_context(): print('Entering') yield print('Leaving') with test_context(): print('Inside') @test_context() def test_decorated(): print('Decorated') test_decorated()
We will yield:
Entering Inside Leaving Entering Decorated …
Continue reading