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 user@subserver.st%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."""

其他提示

pass is used when you want to do nothing, but are syntatically required to have something. I most commonly use it with try...except blocks when I want to simply skip over lines which have an error, as shown below

>>> try:
...    1/0
...
  File "<stdin>", line 3

    ^
SyntaxError: invalid syntax
>>> try:
...    1/0
... except:
...
  File "<stdin>", line 4

    ^
IndentationError: expected an indented block
>>> try:
...    1/0
... except:
...    pass
...
>>>

Empty classes

Empty functions

or, like the other guy said - empty clauses like "except"

There is no point to the use of pass you have shown, it can be removed along with the else. Still, I have found pass useful occasionally, such as when commenting out the body of a conditional, or when implementing a class which has no members:

class dummy:
    pass
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top