Python has a special keyword called pass. The Python pass keyword tells Python to do nothing at all. In other words: just pass this line of code and continue. If you are used to programming in C-like languages, you probably never needed such a statement.
- So why does this keyword exist in Python and not in other languages?
- And where and how would you use it?
This article answers these questions and shows you several situations in which Python’s pass keyword is needed. We’ll also look at an interesting alternative you might like to use instead!
What is the pass keyword
Python’s pass is a keyword, just like if, else, return, and others are keywords. pass doesn’t do anything. It’s a keyword that tells Python to continue running the program, ignoring this line of code. pass is often used as a placeholder for future code.
Note that because pass forms a valid statement on its own, pass can be called a statement too. Hence, you’ll see people using the words pass statement and pass keyword, and it’s both correct.
Why does Python need a pass keyword?
Python relies on indentation. Python can only detect a code block if it is indented with an equal amount of white space (usually four space characters). Python grammar is defined in such a way that code is required in some places. This is done because not adding code in these places would not make much sense and would not help with readability.
Let’s take a look at four places where you must have code. There might be more (please let me know), but these are the most prominent ones. If you don’t enter code in these places, Python will exit the program with an IndentationError exception:
Let’s try some of these for the sake of demonstration:
def myfunction():
# This function has no body, which is not allowed
myfunction()Code language: Python (python)
Python will fail to run this code with the following error:
File "myfile.py", line 4
myfunction()
^
IndentationError: expected an indented block after function definition on line 1
Similar complaints will result in the other cases:
if True:
# No code, not allowed!
else:
# Here too, code is required
try:
# let's try doing nothing (not allowed)
except Exception:
# Again: this can't be empty!
class MyClass:
# A completely empty class is not allowedCode language: Python (python)
As you can see, a comment is not considered code, so comments can’t be used to fill in the gap! This is where the pass statement comes into play. In all the situations above, the pass statement can be used to insert code that does nothing but still satisfies the requirement of having some code in place. Let’s fill in the gaps:
def myfunction():
pass
myfunction()
if True:
pass
else: