3

I found an interesting piece of code in python:

def x(cond):
    if cond:
        pass
        print('Still running!')

x(True)

I would expect this not to print anything, but it prints Still running!. What is happening here?

MattDMo
  • 100,794
  • 21
  • 241
  • 231
J Atkin
  • 3,080
  • 2
  • 19
  • 33

3 Answers3

10

As per Python docs:

pass is a null operation — when it is executed, nothing happens.

Source - https://docs.python.org/3.5/reference/simple_stmts.html#pass

As such, pass does not do anything and all statements after pass will still be executed.

Another way of thinking about this is that pass is equivalent to any dummy statement:

def x(cond):
    if cond:
        "dummy statement"
        print('Still running!')
miki725
  • 27,207
  • 17
  • 105
  • 121
4

pass does not mean "leave the function", it just means ... nothing. Think of it as a placeholder to say that you do not do anything there (for example if you do not have implemented something yet). https://docs.python.org/3.5/tutorial/controlflow.html#pass-statements

If you want to exit the function, you just return or return None

By the way other useful statements are break to exit the latest loop and continue to exit the current iteration of the loop and directly go to the next one.

Mijamo
  • 3,436
  • 1
  • 21
  • 21
  • Yep, I know about all those, I just saw this code and didn't know what it did (I very rarely use python). – J Atkin Jan 24 '16 at 00:54
  • Usually you have two reasons to use pass : you want to implement something in the future so you create the function and leave it empty, or the function is needed because of actions that might happen to an object you just create it but leave it empty because you have no use for it. – Mijamo Jan 24 '16 at 00:59
0

Pass does nothing. When the program gets there, it says "ok skip this!".

Pass can be used to define functions ahead of time. For example,

def function_somebody_is_going_to_write_later():
    pass

def function_I_am_going_to_write_later():
    pass

That way you could write a file with functions that other people might work on later and you can still execute the file for now.

Anton
  • 151
  • 1
  • 10
  • btw alternate method for defining functions is to simply add a docstring. in that case `pass` is not necessary. – miki725 Jan 24 '16 at 01:00
  • Interesting. Is that available in Python 2.7? – Anton Jan 25 '16 at 07:50
  • yes. this is valid in all Python 2.x and 3.x. this trick btw is very useful when writing tests for abc classes: for example http://stackoverflow.com/questions/21351626/how-can-i-test-an-abstract-method-in-python-2-6 – miki725 Jan 25 '16 at 13:01