Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python "with" Keyword in Lambda Functions

Tags:

python

lambda

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()
like image 608
Stephen Niedzielski Avatar asked Apr 26 '13 03:04

Stephen Niedzielski


People also ask

What keywords is used to define lambda function?

What are lambda functions in Python? In Python, an anonymous function is a function that is defined without a name. While normal functions are defined using the def keyword in Python, anonymous functions are defined using the lambda keyword. Hence, anonymous functions are also called lambda functions.

Can lambda expressions contain statements Python?

In particular, a lambda function has the following characteristics: It can only contain expressions and can't include statements in its body. It is written as a single line of execution.

What is Python lambda function give example?

In Python, a lambda function is a single-line function declared with no name, which can have any number of arguments, but it can only have one expression. Such a function is capable of behaving similarly to a regular function declared using the Python's def keyword.


1 Answers

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

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

like image 70
jamylak Avatar answered Oct 27 '22 03:10

jamylak