1

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?

2
  • if you control my_function it would be pretty reasonably to simply check if callback_function: callback_function() Commented Nov 6, 2023 at 19:58
  • But if you don't want to do that, then what you have now is pretty clean as it is. Commented Nov 6, 2023 at 20:21

2 Answers 2

2

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()
Sign up to request clarification or add additional context in comments.

Comments

2

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

2 Comments

I actually think this is less clean than what the OP has.
Yes, including the if statement like in the other answer might be the more 'correct' way of accomplishing OPs requirement. This was just an attempt to keep the theme of a oneliner like was mentioned in the example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.