Skip to main content

Using ContextDecorator with a lambda

In [1]:
from IPython.display import display
from contextlib import ContextDecorator

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

    def __exit__(self, *exc):
        display('Finishing')
        return False
In [2]:
with mycontext():
    display('The bit in the middle')
'Starting'
'The bit in the middle'
'Finishing'
In [3]:
@mycontext()
def function():
    display('The bit in the middle')
    
function()
'Starting'
'The bit in the middle'
'Finishing'
In [4]:
mycontext()(lambda: display('The bit in the middle'))()
'Starting'
'The bit in the middle'
'Finishing'

Comments

Comments powered by Disqus