8

How is Python's with keyword expressed in a lambda function? Consider the following:

def cat (filename):
    with open(filename, 'r') as f:
        return f.read()

A failed attempt at a lambda implementation:

cat = lambda filename: with open(filename, 'r') as f: return f.read()
4
  • Using CPython, your file will be closed immediately after the line open(filename).read() is executed, because the file object is immediately garbage collected. This is an expression and could be used in a lambda. But this is poor style and not a good use case for lambda anyway, using the def is better. Commented Apr 26, 2013 at 3:33
  • Thanks for the input. So for this example, you would simply write open(filename).read() wherever it was needed? Commented Apr 26, 2013 at 3:40
  • you could, which is different from would :) Commented Apr 26, 2013 at 3:45
  • 1
    @StephenNiedzielski Remember that people may run this code on Jython or IronPython for example, which need the actual closing of the file otherwise they have to wait for their garbage collector Commented Apr 26, 2013 at 3:49

2 Answers 2

10

lambda_form ::= "lambda" [parameter_list]: expression

You can't, with is a statement, and lambda only returns expressions.

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for the answer. Is there an alternative for with in the same manner as there is for if? Or is a standard function most practical?
@StephenNiedzielski A standard function, lambdas weren't built for this, Guido also despises them.
for reasons like this, where people try to use lambdas in place of normal functions when they just look less readable. They are useful in some situations, itertools.dropwhile for example, but try not to use them when you can.
A good rule of thumb is if you are assigning the lambda to a name (like you are here, with cat) then something is fishy and it should usually be a def instead. Sometimes lambdas are needed as function call arguments, but even here they are overused and there's often a better alternative.
Stephen, remember that you can use local functions, in case you forgot. The new function doesn't have to pollute the global/module namespace.
|
1

Just in case somebody is looking for a trick:

lambda filename: [(f.read(), f.close()) for f in [open(filename)]][0][0]

2 Comments

This doesn't really answer the question
lambda filename: (f:=open(filename),f.read(),f.close())[1] (python 3.8)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.