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

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