PythonConditional Statements and LoopsPython loop control
What is the `pass` statement?
Question 56 of 88 · Updated
On this page
- 1. How pass behaves inside a loop
- 2. Why Python needs an explicit no-op statement
- 3. Empty functions and classes
- 4. Comments, docstrings, pass and Ellipsis
- 5. Choosing a placeholder that fails explicitly
- 6. Abstract methods
- 7. Practical example: intentionally ignore a specific expected error
- 8. Pass does not prevent assignments or loop progress
- 9. Errors and incorrect assumptions
- 10. When to use pass
- Frequently asked questions
- Is pass the same as continue?
- Does pass return None?
- Can a comment replace pass?
- Is Ellipsis identical to pass?
- Is pass useful in production code?
- Interview-ready answer
- Official references
The pass statement is Python's null operation: executing it does nothing. It is used when the grammar requires a statement but the programmer intentionally has no action to perform. Unlike break or continue, pass does not alter the normal flow of execution.
Pass is useful for intentionally empty function or class bodies, placeholder branches during development and carefully chosen no-action cases. It should not be confused with a successful implementation or an instruction to ignore every error.
1. How pass behaves inside a loop#
PYTHONfor n in range(3): if n==1: pass print(n)
Output:
0
1
2When n equals one, the if suite executes pass. Python then proceeds to the print statement just as it does for the other values. No iteration is skipped.
Replacing pass with continue would skip printing 1. Replacing it with break would end the loop at 1 and prevent printing 1 and 2.
The diagram assumes ordinary control flow without intervening exceptions or required cleanup. The earlier break and continue articles explain those transfers in detail.
2. Why Python needs an explicit no-op statement#
An indented suite following a compound-statement header must contain at least one statement. A blank line or ordinary comment alone cannot satisfy that requirement.
For example, an if header followed only by an indented comment is incomplete. Adding pass makes the intended empty suite syntactically valid.
Pass is a reserved keyword and a complete simple statement. It requires no parentheses, arguments or assignment target. It can be used in function and class bodies, if or else suites, loops and exception-handling suites, among other places where the grammar permits a statement.
3. Empty functions and classes#
PYTHONdef pending(): pass class Marker: pass print(pending() is None, isinstance(Marker(),Marker))
Output:
True TrueThe function is defined normally. Calling it executes its body and reaches the end without an explicit return value, so the function returns None. Pass itself does not return None; the surrounding function's implicit-return rule explains that result.
The class is also created normally. Its body contains no custom attributes or methods, but the resulting class still participates in Python's ordinary class machinery. An instance of Marker is therefore a real object.
Empty classes can be useful as distinct marker types or custom exception types. In contrast, an empty function intended to perform a required operation is unfinished. Its implicit None result can conceal a missing implementation if callers assume the operation succeeded.
4. Comments, docstrings, pass and Ellipsis#
| Construct | Meaning |
|---|---|
# TODO | Source comment; not a statement in an otherwise empty suite |
pass | Null statement |
| A leading string literal in a function or class | Docstring in the designated documentation position |
... | Expression evaluating to the Ellipsis singleton |
return None | Return a value and leave the current function |
raise NotImplementedError(...) | Signal that an operation is not implemented |
A docstring alone is a valid function body because it is a string expression statement with a special documentation role.
PYTHONdef documented(): """A placeholder.""" print(documented.__doc__, documented() is None)
Output under ordinary interpreter settings:
A placeholder. TrueThe function has documentation and still returns None implicitly when called. CPython's -OO optimization can remove docstrings, so do not use them as required application data.
The Ellipsis literal is sometimes used in function stubs and type-stub files. It is a real object, not a keyword equivalent to pass. When used as an expression statement, its value can be discarded.
PYTHONimport ast print(type(ast.parse("pass").body[0]).__name__) print(type(ast.parse("...").body[0]).__name__, ... is Ellipsis)
Output:
Pass
Expr TrueThe abstract syntax tree represents pass with an ast.Pass node. Ellipsis written as a standalone expression instead produces an ast.Expr node containing a constant.
This distinction is useful for tools that inspect Python source. The language guarantees the no-operation semantics of pass; it does not require a particular bytecode instruction or instruction count. Debuggers, tracing tools and implementation-specific compiler optimizations can affect its observable execution overhead.
5. Choosing a placeholder that fails explicitly#
If an operation is required but not implemented, silently doing nothing may be the wrong contract.
PYTHONdef save(): raise NotImplementedError("save not implemented") try: save() except NotImplementedError as exc: print(exc)
Output:
save not implementedA caller immediately learns that the operation is unavailable. An empty save function containing pass would instead finish and return None, which might be misinterpreted as success.
NotImplementedError is an exception. It is distinct from the NotImplemented singleton used by certain binary-operation and rich-comparison protocols to decline an operation with a particular operand type.
Use pass when doing nothing is valid and intentional. Use an explicit exception when executing an unfinished operation must fail. Document the intended behavior rather than relying on a placeholder to communicate a public API contract.
6. Abstract methods#
A base class can define an abstract operation that concrete subclasses must implement. The standard-library abc module provides an enforcement mechanism beyond the empty body itself.
PYTHONfrom abc import ABC, abstractmethod class Writer(ABC): @abstractmethod def write(self, text): pass class MemoryWriter(Writer): def write(self,text): return len(text) print(MemoryWriter().write("abc"))
Output:
3The Writer class declares an abstract method. A concrete subclass implements it. In this deliberately small example, the method only returns the text length; it does not actually persist the text.
The abstractmethod decorator, together with ABC's metaclass machinery, prevents ordinary instantiation of a class with unresolved abstract methods. The pass statement by itself does not provide that enforcement. An ordinary base-class method containing only pass remains callable.
Abstract methods can also contain a meaningful implementation that subclasses call through super. An empty body is one option, not a requirement of the abstract-method mechanism.
7. Practical example: intentionally ignore a specific expected error#
Sometimes the desired result already holds even when an operation raises a particular exception. For example, deleting an optional temporary file is unnecessary if that file does not exist.
PYTHONfrom contextlib import suppress from pathlib import Path from tempfile import TemporaryDirectory with TemporaryDirectory() as tmp: path=Path(tmp)/"missing.txt" try: path.unlink() except FileNotFoundError: pass with suppress(FileNotFoundError): path.unlink() print(path.exists())
Output:
FalseBoth exception-handling forms explicitly ignore FileNotFoundError. The first uses pass in the exception suite. The second uses the standard-library suppress context manager to express the same narrow policy.
The desired postcondition is that the optional file is absent. The example uses an isolated temporary directory and intentionally attempts to delete a nonexistent file. Other errors, such as permission failures, are not caught by these handlers.
For this particular Path.unlink operation, modern Python also supports missing_ok=True, which can express the policy directly.
Avoid a broad except clause followed by pass. It can conceal programming mistakes, interrupted operations and unexpected failures. Catch only the expected exception, keep the protected operation narrowly scoped, and log or propagate unexpected failures according to the application's error policy.
8. Pass does not prevent assignments or loop progress#
PYTHONfor n in range(3): pass print(n) for n in []: pass print(n)
Output:
2
2The first loop still fetches each item and assigns it to n. Its body simply performs no work. After normal exhaustion, n retains its final assigned value. The second loop has an empty iterable, so it never assigns a new value.
Pass is not an instruction to skip evaluation of a loop header, condition or surrounding expression. A condition may call functions or raise exceptions even when its associated suite contains only pass.
A finite loop containing pass still performs iteration and assignment. A permanently truthy while loop containing pass may consume CPU in a busy loop indefinitely. Use a suitable waiting primitive, event or bounded repetition instead of busy waiting when no useful work is being performed.
9. Errors and incorrect assumptions#
The following failure cases were verified independently on the local Python runtime.
| Incorrect source or operation | Expected result |
|---|---|
| An if header followed only by an indented comment | IndentationError |
| A function header followed only by an indented comment | IndentationError |
x = pass | SyntaxError |
| Instantiating an ABC with an unresolved abstract method | TypeError |
Pass is a statement rather than a value-producing expression, so it cannot be assigned to a variable.
Do not confuse pass with an empty collection, None or a false condition. These are values or expression results. Pass means that no operation is specified at that statement's position.
10. When to use pass#
Use pass when a suite intentionally has no action, when creating a marker type or when defining an abstract method whose enforcement is handled separately. It can also be useful for a temporary development scaffold, provided incomplete functionality cannot be mistaken for a successful implementation.
For required functionality, prefer a clearly failing placeholder until the implementation exists. For an intentionally ignored exception, select the specific exception and keep the scope small. For skipping a loop iteration, use continue; for stopping the loop, use break.
A single pass statement performs no application work. It does not make the surrounding function, class construction, condition or loop cost-free. For n iterations of an otherwise empty for loop, traversal still normally requires n item-fetch and assignment steps.
Frequently asked questions#
Is pass the same as continue?#
No. Pass does nothing and ordinary execution proceeds to the following statement. Continue skips the remaining body of the current iteration.
Does pass return None?#
Pass does not return a value. An ordinary function containing only pass returns None because execution reaches the end without an explicit return value.
Can a comment replace pass?#
Not when a statement is required to complete an otherwise empty suite. Comments are not executable statements.
Is Ellipsis identical to pass?#
No. Ellipsis is a singleton value represented by the literal ..., whereas pass is a null statement. Either may be used as an intentional placeholder in some contexts, but their grammar and semantics differ.
Is pass useful in production code?#
Yes, when no action is genuinely the intended behavior. It is risky when used to hide missing implementations or unexpected exceptions.
Interview-ready answer#
Python's pass statement is a syntactic no-op used when a statement is required but no action is intended. It can fill empty functions, classes, branches and exception handlers. Unlike break and continue, it does not transfer control out of a loop or skip an iteration. A function containing only pass returns None through the ordinary implicit-return rule. Pass does not enforce an abstract interface, undo side effects or suppress exceptions by itself. Use it deliberately, and prefer an explicit NotImplementedError when unfinished required functionality must fail visibly.
Official references#
- Python Language Reference — The pass statement
- Python Tutorial — pass Statements
- Python Language Reference — Compound statements
- Python Standard Library — abc
- Python Standard Library — ast
- Python Standard Library — contextlib.suppress
- Python Standard Library — Built-in exceptions
Verification note: All eight fenced Python examples were executed independently on CPython 3.13.5 and matched their documented outputs. Four independent expected-exception tests passed. The Mermaid flowchart was manually reviewed; the Mermaid CLI was unavailable, so parser-level validation and public-site rendering were not performed. Official reference links are supplied under the authorized offline research exception; live documentation and Supabase changelog were not checked.
References
- 1.Python Language Reference — The pass statementdocs.python.org
- 2.Python Tutorial — pass Statementsdocs.python.org
- 3.Python Language Reference — Compound statementsdocs.python.org
- 4.Python Standard Library — abcdocs.python.org
- 5.Python Standard Library — astdocs.python.org
- 6.Python Standard Library — contextlib.suppressdocs.python.org
- 7.Python Standard Library — Built-in exceptionsdocs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design