+
Skip to content

Code Quality

Thomas Perret edited this page Aug 17, 2015 · 14 revisions

Warning : this is a draft version of the document. Do not consider the following as accurate.

Code Checking

You can use pylint to check the quality of your code (the included pylintrc file is automatically used if you execute the command from the python/pyhrf folder):

pylint __init__.py

or check all the package:

pylint pyhrf

You can also configure your editor (vim, emacs, spyder, sublimetext,…) to automatically check your code while writing/editing it. TODO: explain how

Imports

__all__ imports

You should never use the wildcard * import:

from pyhrf import *

because this import all functions that you imported in your module. You can do it if you defined the __all__ variable in your module:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""My marveleous python module"""

__all__ = ['my_super_function', 'MyGeniousClass']

In that case, when you do:

from my_module import *

It will only import my_super_function and MyGeniousClass into your namespace.

Relative imports

You should not use relative imports:

from core import get_data_file_name

instead use absolute imports:

from pyhrf.core import get_data_file_name

PEP8

Try to respect as much as possible the PEP8.

If, for any reason, you can't respect all of it, at least,

You MUST respect:

  1. Indentation with 4 spaces

  2. Operator must be surrounded by spaces:

    var = 'value'
    this == that
    1 + 2

    possible exceptions:

    • grouping priority mathematics operators:
    a = x*2 - 1
    b = x*x + y*y
    c = (a+b) * (a-b)
    • equal sign = in function parameters:
    def function(arg='value'):
      pass
    
    result = function(arg='value')
  3. No spaces in parenthesis, brackets, or curly brackets:

    2 * (3 + 4)
    
    def function(arg='value'):
    
    {str(x): x for x in range(10)}
  4. No spaces before colon and comma, but after:

    def function(arg1='value', arg2=None):
    
    dic = {'a': 1}
  5. Use double quote for stings and docstrings. (Exception if you need a double quote in your string):

    my_string = "This is my string"
    my_other_string = 'I need a "double quote" in my string'
  6. Try to use the new format method from string object:

    >>> print "Hello {0}".format("World")
    Hello World

You SHOULD respect:

  1. Maximum of 80 characters on one line

  2. Variable, class, method, function, constant naming convention

  3. Separate "root" functions and classes by two empty lines and class methods by one empty line

  4. Imports must be on several lines:

    import sys
    import os

    Obvious exception for from import statement:

    from os import path, walk
  5. Imports order and grouping:
    1. Module imports
    2. Module from imports
    3. Standard libraries imports
    4. Standard libraries from imports
    5. External libraries imports
    6. External libraries from imports
    7. Project imports
    import os
    import sys
    
    from itertools import islice
    from collections import namedtuple
    
    import requests
    import arrow
    
    from requests import auth
    from datetime.datetime import date
    
    import scipy
    
    from numpy import cumprod
    
    from pyhrf import FmriData
    from pyhrf.ndarray import xndarray
  6. Encoding declaration:

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
  7. Doctrings for every module, function, class and method

PEP257 (docstrings)

We use the Numpy style docstrings [1]

# -*- coding: utf-8 -*-
"""Example NumPy style docstrings.

This module demonstrates documentation as specified by the `NumPy
Documentation HOWTO`_. Docstrings may extend over multiple lines. Sections
are created with a section header followed by an underline of equal length.

Example
-------
Examples can be given using either the ``Example`` or ``Examples``
sections. Sections support any reStructuredText formatting, including
literal blocks::

    $ python example_numpy.py


Section breaks are created with two blank lines. Section breaks are also
implicitly created anytime a new section starts. Section bodies *may* be
indented:

Notes
-----
    This is an example of an indented section. It's like any other section,
    but the body is indented to help it stand out from surrounding text.

If a section is indented, then a section break is created simply by
resuming unindented text.

Attributes
----------
module_level_variable : int
    Module level variables may be documented in either the ``Attributes``
    section of the module docstring, or in an inline docstring immediately
    following the variable.

    Either form is acceptable, but the two should not be mixed. Choose
    one convention to document module level variables and be consistent
    with it.

.. _NumPy Documentation HOWTO:
   https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt

"""

module_level_variable = 12345


def module_level_function(param1, param2=None, *args, **kwargs):
    """This is an example of a module level function.

    Function parameters should be documented in the ``Parameters`` section.
    The name of each parameter is required. The type and description of each
    parameter is optional, but should be included if not obvious.

    If the parameter itself is optional, it should be noted by adding
    ", optional" to the type. If \*args or \*\*kwargs are accepted, they
    should be listed as \*args and \*\*kwargs.

    The format for a parameter is::

        name : type
            description

            The description may span multiple lines. Following lines
            should be indented to match the first line of the description.

            Multiple paragraphs are supported in parameter
            descriptions.

    Parameters
    ----------
    param1 : int
        The first parameter.
    param2 : str, optional
        The second parameter, defaults to None.
    *args
        Variable length argument list.
    **kwargs
        Arbitrary keyword arguments.

    Returns
    -------
    bool
        True if successful, False otherwise.

        The return type is not optional. The ``Returns`` section may span
        multiple lines and paragraphs. Following lines should be indented to
        match the first line of the description.

        The ``Returns`` section supports any reStructuredText formatting,
        including literal blocks::

            {
                'param1': param1,
                'param2': param2
            }

    Raises
    ------
    AttributeError
        The ``Raises`` section is a list of all exceptions
        that are relevant to the interface.
    ValueError
        If `param2` is equal to `param1`.

    """
    if param1 == param2:
        raise ValueError('param1 may not be equal to param2')
    return True


def example_generator(n):
    """Generators have a ``Yields`` section instead of a ``Returns`` section.

    Parameters
    ----------
    n : int
        The upper limit of the range to generate, from 0 to `n` - 1

    Yields
    ------
    int
        The next number in the range of 0 to `n` - 1

    Examples
    --------
    Examples should be written in doctest format, and should illustrate how
    to use the function.

    >>> print [i for i in example_generator(4)]
    [0, 1, 2, 3]

    """
    for i in range(n):
        yield i


class ExampleError(Exception):
    """Exceptions are documented in the same way as classes.

    The __init__ method may be documented in either the class level
    docstring, or as a docstring on the __init__ method itself.

    Either form is acceptable, but the two should not be mixed. Choose one
    convention to document the __init__ method and be consistent with it.

    Note
    ----
    Do not include the `self` parameter in the ``Parameters`` section.

    Parameters
    ----------
    msg : str
        Human readable string describing the exception.
    code : int, optional
        Error code, defaults to 2.

    Attributes
    ----------
    msg : str
        Human readable string describing the exception.
    code : int
        Exception error code.

    """
    def __init__(self, msg, code=2):
        self.msg = msg
        self.code = code


class ExampleClass(object):
    """The summary line for a class docstring should fit on one line.

    If the class has public attributes, they should be documented here
    in an ``Attributes`` section and follow the same formatting as a
    function's ``Parameters`` section.

    Attributes
    ----------
    attr1 : str
        Description of `attr1`.
    attr2 : list of str
        Description of `attr2`.
    attr3 : int
        Description of `attr3`.

    """
    def __init__(self, param1, param2, param3=0):
        """Example of docstring on the __init__ method.

        The __init__ method may be documented in either the class level
        docstring, or as a docstring on the __init__ method itself.

        Either form is acceptable, but the two should not be mixed. Choose one
        convention to document the __init__ method and be consistent with it.

        Note
        ----
        Do not include the `self` parameter in the ``Parameters`` section.

        Parameters
        ----------
        param1 : str
            Description of `param1`.
        param2 : list of str
            Description of `param2`. Multiple
            lines are supported.
        param3 : int, optional
            Description of `param3`, defaults to 0.

        """
        self.attr1 = param1
        self.attr2 = param2
        self.attr3 = param3

    def example_method(self, param1, param2):
        """Class methods are similar to regular functions.

        Note
        ----
        Do not include the `self` parameter in the ``Parameters`` section.

        Parameters
        ----------
        param1
            The first parameter.
        param2
            The second parameter.

        Returns
        -------
        bool
            True if successful, False otherwise.

        """
        return True

    def __special__(self):
        """By default special members with docstrings are included.

        Special members are any methods or attributes that start with and
        end with a double underscore. Any special member with a docstring
        will be included in the output.

        This behavior can be disabled by changing the following setting in
        Sphinx's conf.py::

            napoleon_include_special_with_doc = False

        """
        pass

    def __special_without_docstring__(self):
        pass

    def _private(self):
        """By default private members are not included.

        Private members are any methods or attributes that start with an
        underscore and are *not* special. By default they are not included
        in the output.

        This behavior can be changed such that private members *are* included
        by changing the following setting in Sphinx's conf.py::

            napoleon_include_private_with_doc = True

        """
        pass

    def _private_without_docstring(self):
        pass

Naming conventions

Indices

One letter in lower case:

for x in range(10):
    print(x)

i = get_index() + 12
print(my_list[i])

Modules, variables, function and methods

Lower case + underscores:

one_variable = 10

def one_function():
    return locals() or {}

class OneClass:
    def a_method_like_every_others(self):
        return globals()

Constants

Upper case + underscores:

MAX_SIZE = 10000000000

Classes

Camel case:

class ThisIsAClass:
    def method(self):
        pass

Exception if there is an acronym:

class HTMLParser:
    def method(self):
        pass

class fMRIComputing:
    def method(self):
        pass

sources :

Official (in english):

PEP8

PEP257

Adapted from (in french):

le PEP8, en résumé

Bien nommer ses variables en Python

[1] See example
Clone this wiki locally
点击 这是indexloc提供的php浏览器服务,不要输入任何密码和下载