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.
An anonymous function returning None is often an appropriate no-op:
def execute(func=lambda *a, **k: None, *args, **kwargs):
return func(*args, **kwargs)
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.
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With