Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass empty/noop function/lambda as default argument

Tags:

python

This is my code:

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

I sometimes want to pass no function f to execute, so I want f to default to the empty function.

like image 223
Randomblue Avatar asked Jan 11 '12 11:01

Randomblue


3 Answers

An anonymous function returning None is often an appropriate no-op:

def execute(func=lambda *a, **k: None, *args, **kwargs):
    return func(*args, **kwargs)
like image 155
minism Avatar answered Nov 08 '22 04:11

minism


The problem is that sometimes want to pass no argument to execute, so I want function to default to the empty function.

Works fine for me:

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

I do note that your example attempts to use f within the implementation, while you've called the parameter function. Could it really be that simple? ;)

That said, you need to understand that Python will have no way to tell that you want to skip the defaulted argument unless there are no arguments at all, so execute(0) cannot work as it attempts to treat 0 as a function.

like image 30
Karl Knechtel Avatar answered Nov 08 '22 03:11

Karl Knechtel


I don't understand very well what are you trying to do
But would 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.

like image 44
Rik Poggi Avatar answered Nov 08 '22 04:11

Rik Poggi