Search code examples
pythoncallbackdefault-parameters

How to write a default parameter callback function that does nothing? [Python]


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?


Solution

  • 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()