Python Lambda Cannot Contain Assignment

Posts: 1,157
Threads: 27
Joined: Sep 2016
Reputation: 22
Likes received: 348

Lambas in Python must be an expression. Assignments are statements. Things like return, break, continue, the equals sign, and that are all statements. While and for loops are also not expressions, although comprehensions are expressions. exec is also a statement, not a function (since functions can be used for expressions) and eval(), though a function, has the same limitation as lambdas that it cannot handle statements.

Basically, you cannot do it this way. You would probably be better off encapsulating the state in a class, and creating a method that mutates that variable internally anyway, e.g.

class State:    def __init__(self):        self.b = False    def setB(self, setTo):        self.b = setTo state = State() SystemHotkey().register(('control', 'e'), callback = lambda: state.setB(True)) # use state.b elsewhere
nilamo likes this post

Lambda Expressions (C# Programming Guide)

A lambda expression is an anonymous function that you can use to create delegates or expression tree types. By using lambda expressions, you can write local functions that can be passed as arguments or returned as the value of function calls. Lambda expressions are particularly helpful for writing LINQ query expressions.

To create a lambda expression, you specify input parameters (if any) on the left side of the lambda operator =>, and you put the expression or statement block on the other side. For example, the lambda expression specifies a parameter that’s named and returns the value of squared. You can assign this expression to a delegate type, as the following example shows:

To create an expression tree type:

The operator has the same precedence as assignment () and is right associative (see "Associativity" section of the Operators article).

Lambdas are used in method-based LINQ queries as arguments to standard query operator methods such as Where.

When you use method-based syntax to call the Where method in the Enumerable class (as you do in LINQ to Objects and LINQ to XML) the parameter is a delegate type System.Func<T,TResult>. A lambda expression is the most convenient way to create that delegate. When you call the same method in, for example, the System.Linq.Queryable class (as you do in LINQ to SQL) then the parameter type is an System.Linq.Expressions.Expression<Func> where Func is any of the Func delegates with up to sixteen input parameters. Again, a lambda expression is just a very concise way to construct that expression tree. The lambdas allow the calls to look similar although in fact the type of object created from the lambda is different.

In the previous example, notice that the delegate signature has one implicitly-typed input parameter of type , and returns an . The lambda expression can be converted to a delegate of that type because it also has one input parameter () and a return value that the compiler can implicitly convert to type . (Type inference is discussed in more detail in the following sections.) When the delegate is invoked by using an input parameter of 5, it returns a result of 25.

Lambdas are not allowed on the left side of the is or as operator.

All restrictions that apply to anonymous methods also apply to lambda expressions. For more information, see Anonymous Methods.

Expression Lambdas

A lambda expression with an expression on the right side of the => operator is called an expression lambda. Expression lambdas are used extensively in the construction of Expression Trees. An expression lambda returns the result of the expression and takes the following basic form:

The parentheses are optional only if the lambda has one input parameter; otherwise they are required. Two or more input parameters are separated by commas enclosed in parentheses:

Sometimes it is difficult or impossible for the compiler to infer the input types. When this occurs, you can specify the types explicitly as shown in the following example:

Specify zero input parameters with empty parentheses:

Note in the previous example that the body of an expression lambda can consist of a method call. However, if you are creating expression trees that are evaluated outside of the .NET Framework, such as in SQL Server, you should not use method calls in lambda expressions. The methods will have no meaning outside the context of the .NET common language runtime.

Statement Lambdas

A statement lambda resembles an expression lambda except that the statement(s) is enclosed in braces:

(input-parameters) => { statement; }

The body of a statement lambda can consist of any number of statements; however, in practice there are typically no more than two or three.

Statement lambdas, like anonymous methods, cannot be used to create expression trees.

Async Lambdas

You can easily create lambda expressions and statements that incorporate asynchronous processing by using the async and await keywords. For example, the following Windows Forms example contains an event handler that calls and awaits an async method, .

You can add the same event handler by using an async lambda. To add this handler, add an modifier before the lambda parameter list, as the following example shows.

For more information about how to create and use async methods, see Asynchronous Programming with async and await.

Lambdas with the Standard Query Operators

Many Standard query operators have an input parameter whose type is one of the Func<T,TResult> family of generic delegates. These delegates use type parameters to define the number and types of input parameters, and the return type of the delegate. delegates are very useful for encapsulating user-defined expressions that are applied to each element in a set of source data. For example, consider the following delegate type:

The delegate can be instantiated as where is an input parameter and is the return value. The return value is always specified in the last type parameter. defines a delegate with two input parameters, and , and a return type of . The following delegate, when it is invoked, will return true or false to indicate whether the input parameter is equal to 5:

You can also supply a lambda expression when the argument type is an , for example in the standard query operators that are defined in System.Linq.Queryable. When you specify an argument, the lambda will be compiled to an expression tree.

A standard query operator, the Count method, is shown here:

The compiler can infer the type of the input parameter, or you can also specify it explicitly. This particular lambda expression counts those integers () which when divided by two have a remainder of 1.

The following line of code produces a sequence that contains all elements in the array that are to the left side of the 9 because that's the first number in the sequence that doesn't meet the condition:

This example shows how to specify multiple input parameters by enclosing them in parentheses. The method returns all the elements in the numbers array until a number is encountered whose value is less than its position. Do not confuse the lambda operator () with the greater than or equal operator ().

Type Inference in Lambdas

When writing lambdas, you often do not have to specify a type for the input parameters because the compiler can infer the type based on the lambda body, the parameter’s delegate type, and other factors as described in the C# Language Specification. For most of the standard query operators, the first input is the type of the elements in the source sequence. So if you are querying an , then the input variable is inferred to be a object, which means you have access to its methods and properties:

The general rules for lambdas are as follows:

  • The lambda must contain the same number of parameters as the delegate type.

  • Each input parameter in the lambda must be implicitly convertible to its corresponding delegate parameter.

  • The return value of the lambda (if any) must be implicitly convertible to the delegate's return type.

Note that lambda expressions in themselves do not have a type because the common type system has no intrinsic concept of "lambda expression." However, it is sometimes convenient to speak informally of the "type" of a lambda expression. In these cases the type refers to the delegate type or Expression type to which the lambda expression is converted.

Variable Scope in Lambda Expressions

Lambdas can refer to outer variables (see Anonymous Methods) that are in scope in the method that defines the lambda function, or in scope in the type that contains the lambda expression. Variables that are captured in this manner are stored for use in the lambda expression even if the variables would otherwise go out of scope and be garbage collected. An outer variable must be definitely assigned before it can be consumed in a lambda expression. The following example demonstrates these rules:

The following rules apply to variable scope in lambda expressions:

  • A variable that is captured will not be garbage-collected until the delegate that references it becomes eligible for garbage collection.

  • Variables introduced within a lambda expression are not visible in the outer method.

  • A lambda expression cannot directly capture a or parameter from an enclosing method.

  • A return statement in a lambda expression does not cause the enclosing method to return.

  • A lambda expression cannot contain a statement, statement, or statement that is inside the lambda function if the jump statement’s target is outside the block. It is also an error to have a jump statement outside the lambda function block if the target is inside the block.

C# Language Specification

For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.

Featured Book Chapter

Delegates, Events, and Lambda Expressions in C# 3.0 Cookbook, Third Edition: More than 250 solutions for C# 3.0 programmers

See Also

C# Programming Guide
LINQ (Language-Integrated Query)
Anonymous Methods
Expression Trees
Visual Studio 2008 C# Samples (see LINQ Sample Queries files and XQuery program)
Recursive lambda expressions


Leave a Reply

Your email address will not be published. Required fields are marked *