I have not seen the keyword pass used much in Python, except for the occasional exception, such as in here: Why is "except: pass" a bad programming practice? Are there any other example use-cases of pass which are acceptable/okay programming practice?

有帮助吗?

解决方案

One use is to define a "stub" class or method that has a name but doesn't do anything. Maybe the most common case of this is to define a custom Exception class:

class MyCustomException(Exception):
    pass

Now you can raise and catch exceptions of this type. The class exists only to be raised and caught, and doesn't need any behavior associated with it.

In similar fashion, APIs may include "do-nothing" functions that are meant to be overridden in subclasses:

class SomeComplexAPI(object):
    # This method may be overridden in subclasses, but the base-class implementation is a no-op
    def someAPIHook(self):
        pass

If you didn't define the method at all, SomeComplexAPI().someAPIHook() would raise an exception because the method doesn't exist. Defining it with pass makes sure you can safely call it even if it doesn't do anything.

其他提示

Here are a few instances where I find myself using pass:

Renaming a class

This is a really common use. 99% of the time it's the Exception class, because it's the easiest way to avoid the bad practice of raising/excepting general exceptions. Example:

class MyModuleException(Exception):
    pass

Declaring a method on a parent class

If subclasses will all be expected to provide a certain method (and that method doesn't have default behavior) I will often define it on the parent class just for documentation purposes. Example:

class Lifeform(object):
    def acquire_energy(source, amount):
        """
        All Lifeforms must acquire energy from a source to survive, but they
        all do it differently.
        """
        pass

Preventing default behavior of inherited methods:

I use this sparingly because generally if you don't want a parent class's method it's a sign that you should either refactor the class hierarchy or that you should have a mix-in class that provides that method. Example:

class Pig(Animal):
    def fly(destination):
        """Pigs can't fly!"""
        pass

Notice here that a better solution would be to add a CapableOfFlight mix-in and remove the Animal.fly() method.

To complement the other good answers, one more case where I find myself using pass is in functions with complex flow, where I want to add comments clarifying the flow. E.g.:

if A:
  if B:
    ...
  else:  # (added only to make the comment below more readable)
    # A and not B: nothing to do because ...
    pass

The else block in this example is obviously not necessary, but I sometimes add it just for making my commentary more readable.

As a way to prevent default behavior (for one example)?

class myClass(MySuper):
  def overriddenmethod(self):
    pass  # Calls to instances of this class will do nothing when this method is called.

pass is useful if you want to make a custom exception:

>>> class MyException(Exception):
...     pass
...
>>> raise MyException("error!")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
__main__.MyException: error!
>>>
>>>
>>> try:
...     raise MyException
... except MyException:
...     print("error!")
...
error!
>>>

In the above example, nothing needs to go inside the class MyException because all I want is a custom exception by that name. So, I use pass as a placeholder to prevent the IndentationError that is raised by not placing anything under the class MyException(Exception) line:

>>> class MyExcpetion(Exception):
...
  File "<stdin>", line 2

    ^
IndentationError: expected an indented block
>>>
>>> class MyExcpetion(Exception):
...     pass
...
>>>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top