How to declare an anonymous function in Python?

Asked

Viewed 1,844 times

7

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

2 answers

8

Use with multiple lines

Basic use the answer of Qmechanic has already given. Python does not have a general use of anonymous functions. Lambda is a specific form of anonymous function that is not commonly used with more than one line codes. In programming using functional style it is very common for expressions to have only one line. Syntax thinks in code concision. If it can’t be concise it probably has something wrong. As they say: "it’s not in the pitonic way".

If this is really necessary the solution is to delegate the 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 executes the action:

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

To use:

funcao([10, -20, 30])

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

I solved the problem of multiple lines and still used Amble in various ways.

General use

Whenever you need to delegate processing to another point in the application it is useful. It is often used to provide Lazy Evaluation. In another question you learned to use it (in PHP) with yield. With Amble you leave the basic processing in charge of a more concrete function that receives the injection of a specific action that will customize this function. So it’s a way to get a better one abstraction by delegation.

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

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

It is obvious that 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 usually a very simple anonymous function that implicitly returns a value (no 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 concepts: Function Pointer, functor, Anonymous Function, fisrt class Function, Function Object, high order Function, nested Function (this I find a little misleading), callback (which is also possible without being exactly a lambda), inline Function (I find this term even more ambiguous).

Implementation

The exact implementation of this mechanism varies from language to language. I don’t 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 the lambda behaves like an enclosure. Normally this object has an extra infrastructure that allows you to manipulate the function in several ways. As far as I know in Python this is provided for any function, also because they all have the ability to use closures, not only Amble. By this in Python it is said that lambda is just a syntactic sugar. You can store normal functions like data.

This object stores temporarily captured variables until no longer needed. The Garbage Collector can solve this although it is easy to leak the resource if it cannot determine the life time accurately. Depends on the quality of the GC in the specific implementation.

High-order functions

Just to quote 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
  • The guy wrote a book for me, man! Thanks

7


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

According to the documentation:

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

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 cannot contain more than one expression, in certain situations where you need to create something more complex than using a normal function instead of a lambda.

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

  • You can do that expression in last lines lambda?

  • 1

    @Wallacemaxters Are one-Lines. That one question cites some reasons for this.

  • @Wallacemaxters You can even do it, but it’s a little bit of style "Pythonic" take a look here.

  • No, let’s follow the pattern. I’ve seen too many tricks in PHP :(

Browser other questions tagged

You are not signed in. Login or sign up in order to post.