The Pass Function in Python
In Python, the "pass" keyword is used only for the pass statement -- a special type of function that is built into the language for the purposes of control flow. When called, it does nothing and simply "passes" program execution to the next line. However, it does perform an important syntactic role in programs.
-
The Pass Statement
-
"Pass" is an empty statement that executes no code. It has two primary purposes. The first is as a placeholder for a function definition that has not been written yet. Using "pass" avoids the compiler errors that would occur if nothing were written where a statement is required. When "pass" is placed as the only statement in the definition, the program will compile successfully, and the function will perform no action when called. For example:
def myFunction(): pass
The pass statement also can be used to "hold" a loop. For example:
while true: pass
Python Structure and the Purpose of the "Pass" Function
-
Unlike other programming languages such as C and Java, Python uses white space and line breaks as delimiters, instead of braces or semi-colons. Function definitions, loop bodies, and other "substructures" are indented after the header. The compiler always expects the line after a header to be part of the definition, and will throw an error if that line is not indented, even if you don't intend it to be part of the loop or function definition. The pass statement is one way to avoid this error.
-
Using Statements in Python
-
Python uses reserved keywords to denote functions and special statements. Statements such as the "pass" statement form the backbone of the code's basic structure. Some other examples of statements include program flow control statements "return" and "break." You do not need parentheses to invoke a statement like "pass" as you do with a true function. Some statements, such as the "print" statement in Python 2, can take parameters, but "pass" does not.
Similar Statements
-
In the context of a loop, other statements can serve a purpose similar to that of the pass statement. For instance, the "continue" statement sends the program to the beginning of the loop as if it had successfully iterated through. In a "while" loop, the "continue" statement serves the same purpose as the "pass" statement: The loop will do nothing and will continue indefinitely until its conditions are met, possibly by a different part of the program sending a signal for the loop to end.
-