def func():
pass
Can anyone describe the use case or give a real time example of the usage of empty functions in python?
def func():
pass
Can anyone describe the use case or give a real time example of the usage of empty functions in python?
One might make empty functions to sketch out a high-level overview of an algorithm, then go in and work on the various functions later; a placeholder basically.
It's arguably whether or not they are "needed", though they can be convenient.
However, I think most would agree that the pass
statement is needed, and function definitions are needed, and what python doesn't need is a special case that prevents you from using pass
as the only statement in a function.
An empty function definition is equally pointless or useful in any language, there's nothing specific to Python here. You may write empty functions in any number of circumstances, from needing a dummy function for testing, for sketching out code, for an abstract class and whatnot.
The only special thing here is Python's pass
, which is simply a syntactical requirement. Where in other languages you may write function () {}
, Python requires you to delimit the function using whitespace and indentation, so you must write something there. And instead of letting everyone define their own convention of how to deal with this situation, pass
exists.
Here is a real example from a project of mine.
The project allows the user to configure arbitrary actions, that can be passed to various parts of the program, so they can trigger a customizable response to specific events.
The user might also have no interest for some events. Yet specifying an action is mandatory, otherwise every single use of an action in the entire project would have to test for None
, that's error-prone).
Thus the DoNothing
action:
class DoNothing(Action):
async def __call__(self, context=None):
pass
(if actions were simple functions it would just be def DoNothing(): pass
but my actions have other methods, which DoNothing doesn't need to override).