Python context manager

Content:

There is a lot I don't know about Python. Saw this mentioned on LinkedIn.

First what most Python developers know - a traditional context manager:

class X:
    def __init__(self):
        print('X.init')
    def m(self):
        print('X.m')

class XWrap:
    def __init__(self):
        print('XWrap.init')
    def __enter__(self):
        print('XWrap.enter')
        return X()
    def __exit__(self, type, value, traceback):
        print('XWrap.exit')
        
with XWrap() as myx:
    myx.m()

Output:

XWrap.init
XWrap.enter
X.init
X.m
XWrap.exit

But now comes the one I did not know:

from contextlib import contextmanager

@contextmanager
def m():
    print('1')
    yield
    print('3')
    
with m():
    print('2')

Output:

1
2
3

Comments: