In Python, what is the difference between pass and return

Return exits the current function or method. Pass is a null operation and allows execution to continue at the next statement.


This illustrates some earlier answers.

def p():
  "Executes both blocks."
  if True:
    print(1)
    pass
  if True:
    print(2)
    pass

def r():
  "Executes only the first block."
  if True:
    print(1)
    return
  if True:
    print(2)
    return

if not instance:
    return # will pass be better or worse here?

Worse. It changes the logic. pass actually means: Do nothing. If you would replace return with pass here, the control flow would continue, changing the semantic of the code.

The purpose for pass is to create empty blocks, which is not possible otherwise with Python's indentation scheme. For example, an empty function in C looks like this:

void foo()
{
}

In Python, this would be a syntax error:

def foo():

This is where pass comes handy:

def foo():
    pass

if not instance:
    return # will pass be better or worse here?

a pass would continue the execution of the method. A return would terminate the execution of the method. Regarding the following lines, you want to put return here.

else:
    return # will a pass be better or worse here?

here it wouldn't make a difference. Even removing the whole two lines wouldn't change anything.

But anyway, imagine you would elaborate the method further. It's better to choose the right flow from the beginning.

Tags:

Python