Search code examples
pythonlambdawith-statementcontextmanager

Use context manager in lambda, how?


How can I use a context manager in a lambda? Hacks accepted. Defer opinions about this being a bad usage of lambdas.

I know I can do this:

def f():
    with context():
        return "Foo"

But I would like to do something like this:

lambda: with context(): "Foo"

Solution

  • One possible workaround for getting lambdas working with a context manager is to make the context manager a ContextDecorator, then both with statements and lambda expressions will work because a lambda can use the decorator pattern instead.

    Example

    from contextlib import ContextDecorator
    
    
    def f(x):
         """Just prints the input, but this could be any arbitrary function."""
         print(x)
    
    
    class mycontext(ContextDecorator):
        def __enter__(self):
            f('Starting')
            return self
    
        def __exit__(self, *exc):
            f('Finishing')
            return False
    
    with mycontext():
        f('The bit in the middle')
    
    mycontext()(lambda: f('The bit in the middle'))()