Development:Coding Standards

Introduction
Any programming project needs coding standards, so that everyone knows what their code needs to look like and can read everyone elses' code easily. Python is a very nice language from this perspective, as it forces the developer to stick to some coding standards by way of indentation and lack of braces. However, this is not all there is to coding standards.

The coding standards we're using in openlp.org 2.0 are based on Python's PEP 8, and a little on Qt's coding standards.

All code should comply now to the PEP8 test tool. To run this use the command python3-pep8 openlp  (this is the fedora command for version 1.4.6).

using a config file in ~/.config/pep8

[pep8] exclude=resources.py,vlc.py max-line-length = 120

Indentation
The most popular way of indenting Python is with 4 spaces, and no tabs. For new projects, spaces-only are strongly recommended over tabs, so we will be using spaces.

Maximum Line Length
Limit all lines to a maximum of 79 80 120 characters. Wrap lines if necessary.

The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. If necessary, you can add an extra pair of parentheses around an expression, but sometimes using a backslash looks better. Make sure to indent the continued line appropriately.

Continuation lines should align wrapped elements either vertically using Python's implicit line joining inside parentheses, brackets and braces, or using a hanging indent. When using a hanging indent the following considerations should be applied; there should be no arguments on the first line and further indentation should be used to clearly distinguish itself as a continuation line.

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 (sparingly) to separate groups of related functions. Blank lines may be omitted between a bunch of related one-liners (e.g. a set of dummy implementations).

Try not to use blank lines in functions, unless you want to specifically indicate logical sections. Use them sparingly.

Encodings
We use UTF-8 in all our files. All code should be in the traditional English alphabet. Use the following comment at the top of every file:

Line endings
Line endings must conform to the UNIX standard ('\n') not the Windows standard ('\r\n').

Many Windows programming text editors/IDE's have a setting to configure this. There are also command line utilities available to convert them (e.g. tofrodos).

In addition, each source file should end with a single blank/empty line.

Imports
Imports should usually be on separate lines, e.g.:

It's okay to import more than one object from the same module, however:

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. Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants. 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 do this:

If this causes local name clashes, then do the following:

Alternately you can rename the class on import:

Always try to be as specific as possible when importing objects. The lower level the import, the more objects you import into memory:

Whitespace
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.

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).

Use spaces around arithmetic operators:

Don't use spaces around the '=' sign when used to indicate a keyword argument or a default parameter value.

Compound statements (multiple statements on the same line) should not be used.

While sometimes it's okay to put an if/for/while with a small body on the same line, never do this for multi-clause statements. Also avoid folding such long lines!

Comments
Comments that contradict the code are worse than no comments. 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 (never alter the case of identifiers!).

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.

Python coders from non-English speaking countries: please write your comments in English, unless you are 120% sure that the code will never be read by people who don't speak your language.

Block Comments
Block comments generally apply to some (or all) 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 (unless it is indented text inside the comment).

Paragraphs inside a block comment are separated by a line containing a single #.

Inline Comments
Use inline comments sparingly.

An inline comment is a comment on the same line as a statement. Inline comments should be separated by at least two spaces from the statement. They should start with a # and a single space.

Inline comments are unnecessary and in fact distracting if they state the obvious. Don't do this:

But sometimes, this is useful:

Names to Avoid
Never use the characters 'l' (lowercase letter el), 'O' (uppercase letter oh), or 'I' (uppercase letter eye) as single character variable names. In some fonts, these characters are indistinguishable from the numerals one and zero. When tempted to use 'l', use 'L' instead.

Package & 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.

Since module names are mapped to file names, and some file systems are case insensitive and truncate long names, it is important that module names be chosen to be fairly short -- this won't be a problem on Unix, but it may be a problem when the code is transported to older Mac or Windows versions, or DOS.

When an extension module written in C or C++ has an accompanying Python module that provides a higher level (e.g. more object oriented) interface, the C/C++ module has a leading underscore (e.g. _socket).

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

Pure Python
All pure Python classes should use the above class naming convention.

Qt/Python Hybrid
All hybrid classes (MediaManagerItem, for example) should use Qt's naming convention, except without the leading Q. All methods within these hybrid classes should also follow Qt's naming convention (def getIcon, for instance).

Exception Names
Because exceptions should be classes, the class naming convention applies here. However, you should use the suffix "Error" on your exception names (if the exception actually is an error).

Functions & Methods
What's the difference?


 * A function is a block of reusable code that can be called from anywhere within an application.
 * A method is a function that is encapsulated in a class.

In short, when "function" is used, it refers to functions outside of classes, and when "method" is used, it refers to function inside of classes.

Naming Conventions
Function and method names should be lowercase, with words separated by underscores as necessary to improve readability. Use one leading underscore only for non-public methods.

Arguments
If a function or method argument's name clashes with a reserved keyword, it is generally better to append a single trailing underscore rather than use an abbreviation or spelling corruption. Thus "print_" is better than "prnt". (Perhaps better is to avoid such clashes by using a synonym.)

Method-specific Arguments
Always use 'self' for the first argument to instance methods and 'cls' for the first argument to class methods.

Instance Variables
Instance variables are better known as properties or attributes. These are variables attached to objects.

Pure Python Objects
Use the function (not method) naming rules: lowercase with words separated by underscores as necessary to improve readability.

Qt-derived Objects
Use the method naming rules for Qt-derived classes: camelCase without exception. Use one leading underscore only for non-public attributes.

Local Variables
Local variables are variables which have been declared within a method or a function, and only exist within the scope and duration of that method or function. These variables are not attached to the object in any way.

Use the function (not method) naming rules: lowercase with words separated by underscores as necessary to improve readability. This rule holds for local variables within methods of any type of class.

Constants
Constants are usually declared on a module level and written in all capital letters with underscores separating words. Examples include MAX_OVERFLOW and TOTAL.

Global Variable Names
The conventions are about the same as those for functions.

Modules that are designed for use via "from M import *" should use the __all__ mechanism to prevent exporting globals, or use the older convention of prefixing such globals with an underscore (which you might want to do to indicate these globals are "module non-public").

Designing for inheritance
Always decide whether a class's methods and instance variables (collectively: "attributes") should be public or non-public. If in doubt, choose non-public; it's easier to make it public later than to make a public attribute 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; you make no guarantees that non-public attributes won't change or even be removed.

We don't use the term "private" here, since no attribute is really private in Python (without a generally unnecessary amount of work).

Another category of attributes are those that are part of the "subclass API" (often called "protected" in other languages). Some classes are designed to be inherited from, either to extend or modify aspects of the class's behavior. When designing such a class, take care to make explicit decisions about which attributes are public, which are part of the subclass API, and which are truly only to be used by your base class.

With this in mind, here are the Pythonic guidelines:


 * Public attributes should have no leading underscores.
 * If your public attribute name collides with a reserved keyword, append a single trailing underscore to your attribute name. This is preferable to an abbreviation or corrupted spelling (however, notwithstanding this rule, 'cls' is the preferred spelling for any variable or argument which is known to be a class, especially the first argument to a class method).
 * For simple public data attributes, it is best to expose just the attribute name, without complicated accessor/mutator methods. Keep in mind that Python provides an easy path to future enhancement, should you find that a simple data attribute needs to grow functional behavior. In that case, use properties to hide functional implementation behind simple data attribute access syntax.
 * If your class is intended to be subclassed, and you have attributes that you do not want subclasses to use, consider naming them with double leading underscores and no trailing underscores. This invokes Python's name mangling algorithm, where the name of the class is mangled into the attribute name. This helps avoid attribute name collisions should subclasses inadvertently contain attributes with the same name.