Skip empty / noop / lambda function as default argument

This is my code:

def execute(f, *args): f(args) 

I sometimes want to pass any function f to execute , so I want f to be an empty function by default.

+7
source share
3 answers

I don’t understand very well what you are trying to do. But is something like this work for you?

 def execute(func=None, *args, **kwargs): if func: func(*args, **kwargs) 

You can also add an else statement to do whatever you like.

+6
source

The problem is that sometimes you need to pass any arguments to execute, so I want the function to be empty by default.

Works great for me:

 >>> def execute(function = lambda x: x, *args): ... print function, args ... function(args) ... >>> execute() <function <lambda> at 0x01DD1A30> () >>> 

I note that your example is trying to use f in the implementation, and you called the function parameter. Is it really that simple ?;)

However, you need to understand that Python will not be able to say that you want to skip the default argument if there are no arguments at all, so execute(0) cannot work because it is trying to treat 0 as a function.

+10
source

An anonymous function returning None is often suitable no-op:

 def execute(func=lambda *a, **k: None, *args, **kwargs): return func(*args, **kwargs) 
+6
source

All Articles