Based on the answers to this question, the pass keyword in Python does absolutely nothing. It simply indicates that "nothing will be done here."
Given this, I don't understand the use of it. For example, I'm looking at the following block of code while trying to debug a script someone else wrote:
def dcCount(server):
ssh_cmd='ssh [email protected]%s' % (server)
cmd='%s "%s"' % (ssh_cmd, sub_cmd)
output=Popen (cmd, shell=True, stdout=PIPE)
result=output.wait()
queryResult=""
if result == 0:
queryResult = output.communicate()[0].strip()
else:
pass
takeData(server, "DC", queryResult)
Is there any purpose at all to having else: pass here? Does this in any way change the way the function runs? It seems like this if/else block could be rewritten like the following with absolutely no change:
if result == 0:
queryResult = output.communicate()[0].strip()
takeData(server, "DC", queryResult)
... or am I missing something? And, if I'm not missing something, why would I ever want to use the pass keyword at all?
It is indeed useless in your example.
It is sometimes helpful if you want a block to be empty, something not otherwise allowed by Python. For instance, when defining your own exception subclass:
class MyException(Exception):
pass
Or maybe you want to loop over some iterator for its side effects, but do nothing with the results:
for _ in iterator:
pass
But most of the time, you won't need it.
Remember that if you can add something else that isn't a comment, you may not need pass. An empty function, for instance, can take a docstring and that will work as a block:
def nop():
"""This function does nothing, intentionally."""
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With