How to declare an anonymous function in Python?

5

How do I declare and how does an anonymous function of Python work?

    
asked by anonymous 12.02.2015 / 11:58

2 answers

5

You can create anonymous functions in Python through an expression lambda .

According to the documentation:

  

Lambda expressions have the same syntactic position as expressions. They are a shortcut to creating anonymous functions; the expression lambda argumentos: expressão produces a function object. The unidentified object behaves as an object with a defined function.

Example:

def foo(x):
   return x*x

It could be done like this:

foo = lambda x: x*x
print(foo(10))
# 100

A function with lambda has no limits on the number of arguments (including optional arguments), it can not contain more than one expression, in certain situations where you need to create something more complex preferably using a normal function instead of lambda .

On its use this is a matter of style, using them is not necessary, but can use anywhere, for example to encapsulate a specific code, in normal functions that have only one line.

    
12.02.2015 / 12:06
6

Use with multiple lines

The basic use of QMechanic's response has already occurred. Python does not have a general way of using anonymous functions. Lambda is a specific form of anonymous function that is not usually used with codes of more than one line. In programming using functional style it is very common for expressions to have only one line. The syntax thinks about code conciseness. If it can not be concise then there is probably something wrong. As they say, "It's not the Python way."

If this is really necessary the solution is to delegate execution to a normal function.

To declare an anonymous function as lambda :

funcao = lambda x: filtro(x, lambda y: y > 0, lambda z: print(z))

The function that actually performs the action:

def filtro(lista, predicado, acao):
    for item in lista:
        if predicado:
            acao(item)

To use:

funcao([10, -20, 30])

See running on ideone .

I solved the problem of multiple lines and still used lambdas in several ways.

General use

Whenever you need to delegate processing to another point in the application, it is useful. It used to be used to provide lazy evaluation . In another question you learned to use this (in PHP) with yield . With lambdas you leave the basic processing handled by a more concrete function that receives the injection of a specific action that will customize this function. So it's a way to get better abstraction through delegation.

In general it is a way to pass algorithms as if they were data. Of course this is optimized and does not pass the source code, usually only a reference is passed to the code that exists elsewhere in the memory.

In some languages its use is seen as positive, in others not, in Python there are opinions everywhere.

Obviously, it is not necessary for anything other than facilitating the work of the programmer.

Terminology

Although each language uses the term in a slightly different way some use other terms for the same thing, lambda is usually a very simple anonymous function that implicitly returns a value (does not need to use a return ) and can capture lexical scope variable as a closure .

Commonly used terms that may mean the same thing or indicate small differences between the concepts: function pointer , functor , anonymous function , < in function function , high order function , nested function (this is a bit misleading), > callback (which is also possible without being exactly a lambda ), inline function (I find this term more ambiguous yet).

Implementation

The exact implementation of this mechanism varies from language to language. I do not know exactly how it was implemented in Python but the most common is that an object is created that has a normal function plus a structure to store captured variables when lambda behaves like a cloister. Usually this object has an extra infrastructure that allows you to manipulate the function in different ways. As far as I know in Python this is provided for any function, since all of them have closures capability, not just lambdas . So in Python it is said that lambda is just a syntactic sugar. You can store normal functions as data.

This object stores temporarily captured variables until you no longer need them. The garbage collector can resolve this although it is easy to leak the feature if it can not accurately determine the lifetime. It depends on the quality of the GC in the specific implementation.

High order functions

Just to name one of the ways to get the same result without using syntax sugar :

def linear(a, b):
    def result(x):
        return a * x + b
    return result

conta = linear(1, 2) //conta será uma função que armazenam estes dois argumentos enclausurados
conta(3) //executa a função result onde a e b valem 1 e 2 respectivamente com argumento 3 p/ x
    
12.02.2015 / 16:30