Code

Python Coding Standard

February 21, 2023
4 min
By
Ramesh
Share

Python is a most useful language these days. If you are going to use it, its better to follow particular standard so that it will be helpful for you and others as well in the future. Here we are describing the coding standards that are followed by ML Team at FCode Labs for their python products.

Naming Conventions

  • Class naming must be done with UpperCamelCase naming style.
  • All variables must follow snake_case naming style.
  • All constants must follow UPPER_CASE naming style.
  • All function naming must be done with snake_case naming style.
  • First argument of class methods must be self.
  • Private variable/method names should start with two underscores.
  • Protected variable/method names should start with single underscore.
  • All class variables (public, protected and private) must be defined inside the __init__() method or method called by the __init__() method. Make sure that this method to be private. Think why?? (hint: polymorphism)
Example for naming convention part 1
Example for naming convention part 2

Programming Rules

  • When testing for None, always use is
  • Do not use brackets in if-statement. (Only use in operator precedence)
Example to not use brackets with if
  • If a class has no base classes, then better to use object class as the base class.
Using object class as the base class
  • Check for membership should use not in
Example to use not in
  • Imports should be grouped in the following order:
  • Standard library imports.
  • Related third party imports.
  • Local application/library specific imports.
Example for import statement convension

Documentation and Spacing

  • Doc-strings should be separated by three double quotes (""")
  • Spacing within a doc-string should be done as mentioned in the following example.
Example for Spacing within a doc-string
  • Should use 4 spaces to indent. (No tabs)
  • When assigning some value to a variable, one space should be used around the equal sign.
  • Every operator should be used between two spaces.
  • But when passing parameters or providing default argument values, do not use space around the equal sign.
  • Should use a space after every comma.
  • Functions and/or classes in a file should be separated with two new lines
  • Methods should be separated with only single new line.
  • Do not use more than one new line inside code body to separate code blocks.
  • Inline comments should have minimum 2 spaces from the end of the code line.
  • There should be at least a single space after the comment sign (#) and before the comment begins.

More