Why would you use the “pass” statement?

Technology CommunityCategory: PythonWhy would you use the “pass” statement?
VietMX Staff asked 3 years ago

Python has the syntactical requirement that code blocks cannot be empty. Empty code blocks are however useful in a variety of different contexts, for example if you are designing a new class with some methods that you don’t want to implement:

class MyClass(object):
    def meth_a(self):
        pass

    def meth_b(self):
        print "I'm meth_b"

If you were to leave out the pass, the code wouldn’t run and you’ll get an error:

IndentationError: expected an indented block

Other examples when we could use pass:

  • Ignoring (all or) a certain type of Exception
  • Deriving an exception class that does not add new behaviour
  • Testing that code runs properly for a few test values, without caring about the results