Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A suitable 'do nothing' lambda expression in python?

Tags:

python

lambda

I sometimes find myself wanting to make placeholder 'do nothing' lambda expressions, similar to saying:

def do_nothing(*args):     pass 

But the following syntax is illegal since lambda expressions attempt to return whatever is after the colon, and you can't return pass.

do_nothing = lambda *args: pass 

So I was wondering, would the following expression be a suitable replacement for the above?

do_nothing = lambda *args: None 

Since the do_nothing function above technically returns None, is it okay to make a lambda expression that returns None to use as a placeholder lambda expression? Or is it bad practice?

like image 952
user3002473 Avatar asked Mar 29 '14 23:03

user3002473


People also ask

How do you return nothing in lambda Python?

Calling type(None) will return you the NoneType constructor, which you can use for doing nothing: type(None)() . Keep in mind that the NoneType constructor only takes 0 arguments. In Python 2, though, creating instances of NoneType is impossible, so lambda: None would make the most sense.

How do you write a lambda expression in Python?

A Python lambda function behaves like a normal function in regard to arguments. Therefore, a lambda parameter can be initialized with a default value: the parameter n takes the outer n as a default value. The Python lambda function could have been written as lambda x=n: print(x) and have the same result.

What is lambda function in Python Support your answer with appropriate code?

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.


1 Answers

This:

def do_nothing(*args):     pass 

is equivalent to:

lambda *args: None 

With some minor differences in that one is a lambda and one isn't. (For example, __name__ will be do_nothing on the function, and <lambda> on the lambda.) Don't forget about **kwargs, if it matters to you. Functions in Python without an explicit return <x> return None. This is here:

A call always returns some value, possibly None, unless it raises an exception.

I've used similar functions as default values, say for example:

def long_running_code(progress_function=lambda percent_complete: None):     # Report progress via progress_function. 
like image 171
Thanatos Avatar answered Sep 20 '22 18:09

Thanatos