Python – Why empty function are needed

functionspythonshell

I started learning Python and I am wondering why empty function are needed in a programming language.

e.g. in python:

def empty_func():
    pass

Even in shell scripts empty functions are available.

My Understandings and question:

  1. Why do programming languages need empty functions? Is it for just playing around with programming language or nothing else that really matters?

  2. If this has a purpose, can anyone describe the use case or give a real example of the usage of empty functions?

  3. Or is there any tradition of programming languages allowing empty functions?

EDIT (Things I got from reading your answers):

  • For Sketching Algorithms or with Abstract Functions
  • For Submitting forms with no action needs to be performed
  • Placeholder for some mandatory operations

Best Answer

In shell languages of the Bourne family, the : command, which does nothing at all, is typically used in two situations:

  • Placeholder for when something expects a mandatory command, e.g.

    while some_condtion
    do :
    done
    

    since do requires at least one command.

  • Discarding the arguments, but performing side effects inside the argument list, e.g.

    : ${myvar=foo}
    

I'm sure there are probably other applications that shell experts would know :)

In Python (and other languages) it's used less frequently. It can act as an argument to a higher-order function when you don't actually want to do anything. For example, say you have a function that submits a form and allows an function to be called asynchronously after submission is complete:

def submit(callback=empty_func):
    ...

This way, if the callback is not provided, the submission will still go through but no further actions will be performed. If you had used None as the default value, you'd have to explicitly check whether the callback was None, adding clutter to the code.

Related Topic