You can't replace the work with
does with an expression, no. There are no hacks to get you there either, because there is no way to handle exceptions and finalisation within an expression.
That's because you can only use one expression in a lambda. with
is a statement, not an expression. You'd have to replace that with exception handling (try..except..finally
) and calls to the __enter__
and __exit__
methods (storing the __exit__
method first). However, exception handling can only be done with statements, because an exception ends the current expression immediately. See Python Try Catch Block inside lambda.
Your only option is to stick to using a proper function instead.