Python PEP 8 standard

Python PEP 8 standard

Pep8 standards are coding convention which help to write python code. The purpose of Pep8 to write a code in such a way it is easily understand for other. The following are the main pep8 standard points.

  1. Variable naming conventions should any one following.
    • underscore_case
      my_name =  "Muhammad Faizan"
      
    • snakeCase
      myName = "Muhammad Faizan"
      
    • PascalCase
      MyName = "Muhammad Faizan"
      
  2. Constant variable names should name all the capital letter.
    MY_NAME = "Muhammad Faizan"
    
  3. Name of the user-defined function name should be underscore case.
    def hello_greet():
    return "hello"
    
  4. Class name should be start from capital character

    • 'self' should be first name in class function.
      class Person:
      
  5. import all libraries should be on top and if you import something from same module in single line is OK. Avoid to use asterik to import all the things from file.

    • Correct
      from calculation import add, sub, mul
      
    • Wrong
      from calculation import *
      
  6. Don't use unnecessary white spaces.
  7. Don't use white spaces in default parameter of user-defined function.
  8. Inline comment should be following
    • Correct:
      user_name = 'muhammad_faizan'  # name of user
      
    • Wrong:
      user_name = 'muhammad_faizan' #name of user
      
  9. Validating the variable.

    • Correct:
      x = None
      if x is None:
        pass
      
    • incorrect:

      if x:
         pass
      
    • Wrong:

      if x == None:
         pass
      
  10. Checking the desired character in variable.

    • Correct

      user_name = 'muh_faizan'  # name of user 
      if user_name.startswith('muh'):
        print("correct")
      
    • Correct

      if user_name.endswith('faizan'):
        print("correct")
      
    • Wrong:

      if username[:3] == 'muh':
        print("correct")
      

Reference: peps.python.org/pep-0008/#whitespace-in-exp..