简体   繁体   中英

Using a lambda function in python

Is there a way to convert a function to a lambda function (automatically) in python? Something like:

def func(arg):
    print("Hi", arg)

==>

lambda arg: compile(func) # <== something like this

Functions in Python are first-class citizens of the language. This means that a function can be manipulated as if it was a data value. Thus, a function can be passed to another function as an argument, or returned from a function as a result. This is referred to as higher-order programming .

Now, both the def and the lambda keywords define such function values. The main difference is that def assigns a name to such a function, whereas lambdas are anonymous functions. Another difference is that lambdas are limited to one line of code (although there are languages where this is not the case).

For example, here are two equivalent functions, one defined with def , the other with lambda :

def say_hello(name):
    print('Hi ', name)

lambda name: print('Hi ', name)

Another way to interpret the def keyword is as follows:

say_hello = lambda name: print('Hi ', name)

Although such code is highly discouraged.

In essence, both of these two functions are (nearly) equivalent data values, but in the snippet above, the one defined with def could later be called, since it has a name and we can therefore later access it. The one defined by lambda cannot, since it does not have a name, and is thus immediately lost if not assigned to a variable or passed to another function, say f , as an argument, where it is then given a name in f 's local scope as per the f 's parameters.

However, lambdas are useful in cases where we do not want to clutter up our scope with new, short functions that are only passed to another function as an argument:

map(lambda x: x * 2, [1, 2, 3])
# >>> [2, 4, 6]

If you already have a function defined with def that does the multiplication shown above, as would be the case in your example, eg:

def double(x):
    return x * 2

Then you can simply refer to this function by name in the call to map:

map(double, [1, 2, 3])
# >>> [2, 4, 6]

In short: There is no need to "compile a function to a lambda", a lambda is just a special case of a function which is not given a name. Refer to your function by name instead.

PS: Don't use map and filter , use list comprehensions instead, as they are considered more pythonic.

You can make yours easily:

def auto_lam(f):
  return lambda *args, **kwargs: f(*args, **kwargs)

Then to use it:

mylam = auto_lam(func)

In this form, you can see that this is quite useless because you are simply calling the same function, but wrapping functions is something that is very common in python because it allows us to modify the behaviour of the function. These are called decorator functions .

For example:

def logging_func(f):
    def do_work(*args, **kwargs):
        print ("You called me")
        res = f(*args, **kwargs)
        print ("Finished")
        return res
    return do_work

Now you can wrap your existing function with this one like so:

@logging_func
def func(arg):
   print("Hi", arg)

Now every time you call func , it will log something before and after. I argue this is a better use of function wrappers than one that simply gives you back the same function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM