Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

I want to pass in a callback function as a parameter to my_function sometimes. However, I want the default behavior to simply just 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()

That doesn’t work, so the best valid solution I have come up with is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading