How to use the pass statement?

前端 未结 15 2366
旧时难觅i
旧时难觅i 2020-11-22 15:03

I am in the process of learning Python and I have reached the section about the pass statement. The guide I\'m using defines it as being a Null sta

相关标签:
15条回答
  • 2020-11-22 15:16

    The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute.

    The pass statement is a null operation; nothing happens when it executes. The pass is also useful in places where your code will eventually go, but has not been written yet (e.g., in stubs for example):

    `Example:

    #!/usr/bin/python
    
    for letter in 'Python': 
       if letter == 'h':
          pass
          print 'This is pass block'
       print 'Current Letter :', letter
    
    print "Good bye!"
    

    This will produce following result:

    Current Letter : P
    Current Letter : y
    Current Letter : t
    This is pass block
    Current Letter : h
    Current Letter : o
    Current Letter : n
    Good bye!
    

    The preceding code does not execute any statement or code if the value of letter is 'h'. The pass statement is helpful when you have created a code block but it is no longer required.

    You can then remove the statements inside the block but let the block remain with a pass statement so that it doesn't interfere with other parts of the code.

    0 讨论(0)
  • 2020-11-22 15:17

    Pass refers to ignore....as simple as it is ....if the given condition is true and the next statement is pass it ignores that value or iteration and proceed to the next line ..... Example

    For i in range (1,100):
        If i%2==0:
                      Pass 
        Else:
                      Print(i)
    

    Output: Prints all the odd numbers from 1-100

    This is because modulus of even number is equal to zero ,hence it ignores the number and proceeds to next number ,since odd numbers modulus is not equal to zero the Else part of the loop is executed and its printed

    0 讨论(0)
  • 2020-11-22 15:19

    Here's an example where I was extracting particular data from a list where I had multiple data types (that's what I'd call it in R-- sorry if it's the wrong nomenclature) and I wanted to extract only integers/numeric and NOT character data.

    The data looked like:

    >>> a = ['1', 'env', '2', 'gag', '1.234', 'nef']
    >>> data = []
    >>> type(a)
    <class 'list'>
    >>> type(a[1])
    <class 'str'>
    >>> type(a[0])
    <class 'str'>
    

    I wanted to remove all alphabetical characters, so I had the machine do it by subsetting the data, and "passing" over the alphabetical data:

    a = ['1', 'env', '2', 'gag', '1.234', 'nef']
    data = []
    for i in range(0, len(a)):
        if a[i].isalpha():
            pass
        else:
            data.append(a[i])
    print(data)
    ['1', '2', '1.234']
    
    0 讨论(0)
  • 2020-11-22 15:22

    Python has the syntactical requirement that code blocks (after if, except, def, class etc.) cannot be empty. Empty code blocks are however useful in a variety of different contexts, such as in examples below, which are the most frequent use cases I have seen.

    Therefore, if nothing is supposed to happen in a code block, a pass is needed for such a block to not produce an IndentationError. Alternatively, any statement (including just a term to be evaluated, like the Ellipsis literal ... or a string, most often a docstring) can be used, but the pass makes clear that indeed nothing is supposed to happen, and does not need to be actually evaluated and (at least temporarily) stored in memory.

    • Ignoring (all or) a certain type of Exception (example from xml):

      try:
          self.version = "Expat %d.%d.%d" % expat.version_info
      except AttributeError:
          pass # unknown
      

      Note: Ignoring all types of raises, as in the following example from pandas, is generally considered bad practice, because it also catches exceptions that should probably be passed on to the caller, e.g. KeyboardInterrupt or SystemExit (or even HardwareIsOnFireError – How do you know you aren't running on a custom box with specific errors defined, which some calling application would want to know about?).

      try:
          os.unlink(filename_larry)
      except:
          pass
      

      Instead using at least except Error: or in this case preferably except OSError: is considered much better practice. A quick analysis of all python modules I have installed gave me that more than 10% of all except ...: pass statements catch all exceptions, so it's still a frequent pattern in python programming.

    • Deriving an exception class that does not add new behaviour (e.g. in scipy):

      class CompileError(Exception):
          pass
      

      Similarly, classes intended as abstract base class often have an explicit empty __init__ or other methods that subclasses are supposed to derive. (e.g. pebl)

      class _BaseSubmittingController(_BaseController):
          def submit(self, tasks): pass
          def retrieve(self, deferred_results): pass
      
    • Testing that code runs properly for a few test values, without caring about the results (from mpmath):

      for x, error in MDNewton(mp, f, (1,-2), verbose=0,
                               norm=lambda x: norm(x, inf)):
          pass
      
    • In class or function definitions, often a docstring is already in place as the obligatory statement to be executed as the only thing in the block. In such cases, the block may contain pass in addition to the docstring in order to say “This is indeed intended to do nothing.”, for example in pebl:

      class ParsingError(Exception): 
          """Error encountered while parsing an ill-formed datafile."""
          pass
      
    • In some cases, pass is used as a placeholder to say “This method/class/if-block/... has not been implemented yet, but this will be the place to do it”, although I personally prefer the Ellipsis literal ... in order to strictly differentiate between this and the intentional “no-op” in the previous example. (Note that the Ellipsis literal is a valid expression only in Python 3)
      For example, if I write a model in broad strokes, I might write

      def update_agent(agent):
          ... 
      

      where others might have

      def update_agent(agent):
          pass
      

      before

      def time_step(agents):
          for agent in agents:
              update_agent(agent)
      

      as a reminder to fill in the update_agent function at a later point, but run some tests already to see if the rest of the code behaves as intended. (A third option for this case is raise NotImplementedError. This is useful in particular for two cases: Either “This abstract method should be implemented by every subclass, there is no generic way to define it in this base class”, or “This function, with this name, is not yet implemented in this release, but this is what its signature will look like”)

    0 讨论(0)
  • 2020-11-22 15:23

    The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action.

    0 讨论(0)
  • 2020-11-22 15:24

    pass in Python basically does nothing, but unlike a comment it is not ignored by interpreter. So you can take advantage of it in a lot of places by making it a place holder:

    1: Can be used in class

    class TestClass: 
        pass
    

    2: Can be use in loop and conditional statements:

    if (something == true):  # used in conditional statement
        pass
       
    while (some condition is true):  # user is not sure about the body of the loop
        pass
    

    3: Can be used in function :

    def testFunction(args): # programmer wants to implement the body of the function later
        pass
    

    pass is mostly used when programmer does not want to give implementation at the moment but still wants to create a certain class/function/conditional statement which can be used later on. Since the Python interpreter does not allow for blank or unimplemented class/function/conditional statement it gives an error:

    IndentationError: expected an indented block

    pass can be used in such scenarios.

    0 讨论(0)
提交回复
热议问题