Wednesday, 8 August 2012

GUIDELINES TO WRITE A PROGRAM IN PYTHON


GUIDELINES TO WRITE A PROGRAM IN PYTHON.
  • The guidelines provided here are intended to improve the readability of code and make it consistent across the wide spectrum of Python code.
  • The guidelines is about consistency. Consistency with this style guide is important. Consistency within a project is more important.
  • Break the rules, if it hinders the readability of the code.
     CODE LAY OUT
     Indentation:
  • Use 4 spaces per indentation level.
  • Continuation lines should align wrapped elements either vertically or using a hanging indent.
  • Eg:
         def long_function_name(
                     var_one, var_two, var_three
                     var_four):
            print( var_one )
     Tabs or Spaces?:
  • Never mix tabs and spaces.
  • Either follow indenting Python with spaces only or tabs only.
     Maximum Line Length:
  • Limit all lines to a maximum of 79 characters.
  • Wrapping long lines is done by using Python's implied line continuation inside parentheses, brackets and braces.
  • The preferred place to break around a binary operator is after the operator, not before it.
  • Eg:
   class Rectangle(Blob):
       def __init__ (self, width, height,
                     color='black', emphasis=None highlight=0):
           if (width == 0 and height == 0 and
               color == 'red' and emphasis == 'strong' or
               highlight > 100);
               raise ValueError("sorry you lose")
           if width == 0 and height == 0 and (color == 'red' or
                                              emphasis is None):
               raise ValueError("I don't think so -- values are %s,
                                %s" (width,height))
           Blob.__init__(self, width, height,
                         color, emphasis,highlight)
  
     Blank Lines:
  • Separate top-level function and class definitions with two blank lines.
  • Method definitions inside a class are separated by a single blank line.
  • Extra blank lines may be used to separate groups of related functions.
  • Use blank lines in functions, sparingly, to indicate logical sections.
     Encodings:
  • Code in the core Python distribution should always use the ASCII or Latin-1 encoding.
  • For Python 3.0 and beyond, UTF-8 is preferred over Latin-1.
  • Files using ASCII should not have a coding cookie.
  • Latin-1 (or UTF-8) should only be used when a comment or docstring needs to mention an author name that requires Latin-1; otherwise, using \x, \u or \U escapes is the preferred way to include non-ASCII data in string literals.
  • All identifiers in the Python standard library MUST use ASCII-only identifiers, and SHOULD use English words wherever feasible.
  • The only exceptions are
    (a) test cases testing the non-ASCII features, and
    (b) names of authors.
      Imports:
  • Imports should usually be on separate lines.
  • Eg:
              import os
         import sys.
  • Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.
  • Imports should be grouped in the following order:
          1. standard library imports
          2. related third party imports
          3. local application/library specific imports .
    You should put a blank line between each group of imports.
    Put any relevant __all__ specification after the imports.
  • Relative imports for intra-package imports are highly discouraged. Always use the absolute package path for all imports.
  • When importing a class from a class-containing module, it's usually okay to spell this:
                      from myclass import MyClass
                      from foo.bar.yourclass import YourClass.

      Whitespace in Expressions and Statements:
  • Avoid extraneous whitespace in the following situations:
  • Immediately inside parentheses, brackets or braces.
  • Immediately before a comma, semicolon, or colon.
  • Immediately before the open parenthesis that starts the argument list of a function call.
  • Immediately before the open parenthesis that starts an indexing or slicing.
  • More than one space around an assignment (or other) operator to align it with another.

      Other Recommendations:
  • Always surround these binary operators with a single space on either side: assignment (=), augmented assignment (+=, -= etc.), comparisons (==, <, >, !=, <>, <=, >=, in, not in, is, is not), Booleans (and, or, not).
  • If operators with different priorities are used, consider adding whitespace around the operators with the lowest priority(ies). Never use more than one space, and always have the same amount of whitespace on both sides of a binary operator.
  • Eg:
    i = i + 1
    submitted += 1
    x = x * 2 - 1
    hypot2 = x * x + y *y
  • Don't use spaces around the = sign when used to indicate a keyword argument or a default parameter value.
  • Eg:
        def complex(real, imag=0.0):
             return magic(r=real, i=imag).
  • Compound statements (multiple statements on the same line) are generally discouraged.
     Comments:
  • Comments should not be contradict. Always make a priority of keeping the comments up-to-date when the code changes!
  • Comments should be complete sentences. If a comment is a phrase or sentence, its first word should be capitalized, unless it is an identifier that begins with a lower case letter .
  • If a comment is short, the period at the end can be omitted. Block comments generally consist of one or more paragraphs built out of complete sentences, and each sentence should end in a period.
  • You should use two spaces after a sentence-ending period.
  • When writing English, Strunk and White apply.

     Block Comments:
  • Block comments generally apply to code that follows them, and are indented to the same level as that code.
  • Each line of a block comment starts with a # and a single space.
  • Paragraphs inside a block comment are separated by a line containing a single #.

      Inline Comments:
  • Use inline comments sparingly.
  • Inline comments should be separated by at least two spaces from the statement.
  • They should start with a # and a single space.

     Documentation Strings:
  • Docstrings explain how to use code, and are for the users of your code.
  • Explain the purpose of the function, help full to someone else later on.
  • Describe the parameters expected, the return values, and any exceptions raised.
  • Docstrings are useful in interactive use (help()) and for auto-documentation systems.

     Naming Conventions:
  • joined_lower for functions, methods, attributes.
  • joined_lower or ALL_CAPS for constants.
  • StudlyCaps for classes.
  • camelCase only to conform to pre-existing conventions.

     Prescriptive: Naming Conventions:
     Names to Avoid:
  • Never use the characters 'l' , 'O' , or 'I' as single character variable names.

     Package and Module Names:
  • Modules should have short, all-lowercase names.
  • Underscores can be used in the module name if it improves readability.]
  • Python packages should also have short, all-lowercase names, although the use of underscores is discouraged.
  • It is important that module names be chosen to be fairly short .

     Class Names:
  • Almost without exception, class names use the CapWords convention.
  • Classes for internal use have a leading underscore in addition.

     Exception Names:
  • Because exceptions should be classes, the class naming convention applies here. You should use the suffix "Error" on your exception names.

     Functional Names:
  • Function names should be lowercase, with words separated by underscores as necessary to improve readability.
     Method Names and Instance Varibles:
  • Use the function naming rules: lowercase with words separated by underscores as necessary to improve readability.
  • Use one leading underscore only for non-public methods and instance variables.
  • To avoid name clashes with subclasses, use two leading underscores to invoke Python's name mangling rules.
     Constants:
  • Constants are usually defined on a module level and written in all capital letters with underscores separating words.

      Designing for Inheritance:
  • Always decide whether a class's methods and instance variables should be public or non-public.
  • Public attributes are those that you expect unrelated clients of your class to use, with your commitment to avoid backward incompatible changes.
  • Non-public attributes are those that are not intended to be used by third parties.
  • Another category of attributes are those that are part of the "subclass API"

No comments:

Post a Comment