Manual:Coding conventions/Python

This page describes the coding conventions for Python projects that are a part of the MediaWiki project or supporting projects.

Code Standards
For anything not covered in this document, please refer to Python Enhancement Proposal 0008 for the general practice. The following sections are for the most part a summary of the most commonly referred to parts of PEP8.

Whitespace
Lines should be indented with 4 spaces.

Lines at the end of files should end with a newline, just like every other line in the file.

Lines should be a maximum of 79 characters long. Yes, we don't all program on VT100 terminals anymore, but it's quite nice to be able to pull up a few files side-by-side even on a smallish screen. Here are some standard ways to do line continuations.

Module Structure
The standard way to distribute python modules is to create a setup.py file and leverage a library called "distribute". There are modules that will generate the structure of a base project for you, a deprecated one is  which is no longer maintained. A replacement is pythong.

In general module structure should look like this: newproject ├── bin ├── distribute_setup.py ├── docs ├── newproject │   └── __init__.py ├── setup.py └── tests ├── __init__.py   └── newproject_tests.py

Imports
Within a file it's generally a good idea to organize your imports in some fashion. Typically alphabetical order is favored, but this can become unwieldy when importing a large number of libraries. To help avoid this, it's good to separate out imports in this fashion:
 * Standard library imports
 * Third party imports
 * Your library imports

Here are some patterns to avoid:

Docstrings and Function Annotation
Generally all but the simplest functions should have docstrings. These are standardized in PEP 257

This makes it possible to automatically generate docs, as well as use Python's built-in  function.

In Python 3.3 and above PEP 3107 specifies syntax for function annotations.

Function annotations do not have a completely set use case, but a common emerging case is for improved help docs and for type annotation.

Naming Conflicts
Conflicting with builtins is a somewhat common problem. There are some builtin names (like  and  ) that you may want to use in your code. The PEP8 way to deal with these conflicts is by appending an underscore to the name, such as  or   (although if you're naming a variable   that may be a code smell).

If you find yourself in conflict with the name of some part of another module,  is your friend.