11

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.

2
  • 1
    What error message? And why is your parameter named function, but you call f? Commented Jan 11, 2012 at 11:08
  • 3
    You probably got the error message global name 'f' is not defined because, well, f is not defined. If you got a different error message, please specify which one (full traceback, please). Commented Jan 11, 2012 at 11:09

3 Answers 3

13

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Sorry, the question was terribly worded. I have rewritten it.
To make it even more generic, make it lambda *x, **xx: None. Now it's effectively an universal no-op function -- it accepts any number of arguments and keyword arguments.
8

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

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

2 Comments

I guess this means there isn't any shorter notation for lambda *a, **k: None. I tried out func=pass, but of course that didn't work.
This should ideally be the top answer, as it prevents a lot of headaches when passing additional arguments to func within execute (say, if one of the arguments was created within execute and not passed as a parameter). Not sure if this applies here because OP gave a very bare-bones example. Using func=None as the default is a bit messy; requiring conditionals and additional type-hinting.
4

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.

2 Comments

Yeah, that works. I was trying to get rid of this if statement.
in this if func is def func(): pass. You don't need the if. just func(*args, **kwargs)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.