Reputation: 387
I sometimes want to pass in a callback function as a parameter to my_function
. However, I want the default behavior to simply do nothing.
I find myself wanting to write the following invalid lines of code:
def my_function(args, callback_function=pass):
# do something
callback_function()
But that doesn't work, so the best valid solution I have come up with is:
def do_nothing():
pass
def my_function(args, callback_function=do_nothing):
# do something
callback_function()
Is there a cleaner way to do this, more like the first example above?
Upvotes: 1
Views: 393
Reputation: 36340
You might elect to accept None
and only call callback_function
when it is not None
, that is
def my_function(args, callback_function=None):
# do something
if callback_function is not None:
callback_function()
Upvotes: 2
Reputation: 146
Calling 'None' should do what you're asking. 'pass' is a keyword and is not callable like that. None is a default value and can be applied using lambda.
def my_function(args, callback_function=lambda: None):
# do something
callback_function()
Upvotes: 2