Saturday 11 August 2012

Python Coding Style

 

Python Programming Style

         Programming style is a set of rules or guidelines used when writing the source code for a computer program. It is often claimed that following a particular programming style will help programmers to read and understand source code conforming to the style, and help to avoid introducing errors.

        In python readability counts.Python community has its own standards  as that of C,C++,etc.
Python Enhancement Proposal(PEP)8 is a style guide for python which describe what a python code should look like .

 

White spaces

  • 4 spaces per indentation .
  • Never mix spaces and tabs.
  • Add a space after ',' in dictionaries and argument list and after ':' in dictionaries
  • Put spaces around assignments and comparisions.

 

Naming

  • Lower case for functions,methods,attributes
  • All caps for constants
  • _name becomes _classname__name avoid such usage as it may create problems when a subclass may need to access the same variable
  • The above situation requires either the super class or the sub class has to changed

 

Long Lines 

  • Keep lines below 79 characters
  • Use backslashes as a last resort

 

Compound Statements

  • Avoid the over use of ';' in blocks of codes,as it effect the readability of the code drastically
  • May be used at some circumstances,if this sacrifice may result in a better readability.

 

Docstrings and Comments

  • Docs string are used to specify how to use code
  • Comments Specify why and how code works
  • It is better not to specify a comment rather then a miss-leading comment.

 

Building Strings

  • Make use of ''.join() method as far as possible as it improves the performance during passing

     

Testing for Truth Values

   if x :
       print something

   Is  Better than

   if x==0 True:
      print something

 

variables

  • In python identifier are like parcel tag attached to an object.
  • Hence an identifier can becomes a tag of any object

 

Importing

  • While importing we have to import standard modules.First followed by third party modules and at last the local modules




No comments:

Post a Comment