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.
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.
lambda *x, **xx: None. Now it's effectively an universal no-op function -- it accepts any number of arguments and keyword arguments.An anonymous function returning None is often an appropriate no-op:
def execute(func=lambda *a, **k: None, *args, **kwargs):
return func(*args, **kwargs)
lambda *a, **k: None. I tried out func=pass, but of course that didn't work.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.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.
if statement.
function, but you callf?global name 'f' is not definedbecause, well,fis not defined. If you got a different error message, please specify which one (full traceback, please).