Reputation: 251
I have a piece of code that defines a function that takes a function as an argument, like so:
def stuff(n, f):
f(n)
Now, I want to provide some default value of f that does nothing. So I figured I'd use pass, like so:
def stuff(n, f = None):
if(f is None):
f = pass
f(n)
But this does not compile. How should I be doing this?
Upvotes: 8
Views: 2821
Reputation: 517
I'd go with a
def nop(*args, **kwargs):
pass
def algo(func=nop):
do_something()
func()
do_something_else()
algo() # nop is called
algo(some_callback) # some_callback is called
IMHO looks cleaner than
if foo:
foo()
Upvotes: 1
Reputation: 101
The generic noop function :
f = lambda *x,**y:None
You can call
f()
f(0,foo=0)
Upvotes: 3
Reputation: 4282
Why not simply this ?
def stuff(n, f=None):
if f is None:
return
return f(n)
Upvotes: 9
Reputation: 76856
A little shorter:
def stuff(n, f=None):
f = f or (lambda x: None)
f(n)
Or even better:
def stuff(n, f=None):
f(n) if f is not None else None
Upvotes: 5
Reputation: 43054
The pass
is a keyword for the interpreter, a place holder for otherwise nothing. It's not an object that you can assign. You can use a no-op lambda.
f = lambda x: None
Upvotes: 19
Reputation: 42208
You can't assing empty. But you can creaty internal function, that you will assign to f
.
def stuff(n, f=None):
def empty(n):
pass
if f is None:
f = empty
f(n)
Upvotes: 4