2.3. Python Coding Guidelines

These coding guidelines MUST be applied to all Python files.

The source files MUST be successfully checked by running the waf command check_guidelines before files can be merged into the master branch of the repository.

The following rules generally apply and follow the naming schema PYTHON:<ongoing-number>.

2.3.1. Filenames (PYTHON:001)

The following rules apply for filenames of Python scripts.

Python Script Filenames

  • The general file naming rules MUST be applied (see Section 2.1.1), except that dashes (-) SHOULD not be used.

  • Python scripts MUST use .py as file extension, except for waf build scripts which use wscript as file name.

For example the valid file names for batch scripts are

  • hello.py

  • my-script.py (not recommended, as the script is not importable)

  • my_script.py (recommended, the script is importable)

2.3.2. Header (PYTHON:002)

Python file header

Python source and header files MUST start with the following header:

Listing 2.37 File header for .py files.
 1#!/usr/bin/env python3
 2# -*- coding: utf-8 -*-
 3#
 4# Copyright (c) 2010 - 2021, Fraunhofer-Gesellschaft zur Foerderung der angewandten Forschung e.V.
 5# All rights reserved.
 6#
 7# SPDX-License-Identifier: BSD-3-Clause
 8#
 9# Redistribution and use in source and binary forms, with or without
10# modification, are permitted provided that the following conditions are met:
11#
12# 1. Redistributions of source code must retain the above copyright notice, this
13#    list of conditions and the following disclaimer.
14#
15# 2. Redistributions in binary form must reproduce the above copyright notice,
16#    this list of conditions and the following disclaimer in the documentation
17#    and/or other materials provided with the distribution.
18#
19# 3. Neither the name of the copyright holder nor the names of its
20#    contributors may be used to endorse or promote products derived from
21#    this software without specific prior written permission.
22#
23# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
24# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
26# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
27# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
29# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
30# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
31# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
32# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33#
34# We kindly request you to use one or more of the following phrases to refer to
35# foxBMS in your hardware, software, documentation or advertising materials:
36#
37# - "This product uses parts of foxBMS®"
38# - "This product includes parts of foxBMS®"

2.3.3. Syntax (PYTHON:003)

The following rules apply for syntax of Python scripts

Python syntax rules

  • Python 2 only syntax MUST NOT be used.

  • Python 3 only syntax MAY be used.

  • Code MUST work in Python 3.6 or greater.

2.3.4. Formatting (PYTHON:004)

Uniform formatting makes code easier to read to all developers.

Python formatting rules

Python source files are checked for correct formatting by black. The black configuration can be found in conf/fmt/pyproject.toml.

2.3.5. Static program analysis (PYTHON:005)

Static program Analysis helps to detected code smells and errors in an early stage of development.

Python static program analysis rules

Python sources files are statically checked by pylint. The pylint configuration can be found in conf/spa/.pylintrc.

2.3.6. No platform specific code (PYTHON:006)

No platform specific code

Python scripts MUST use platform independent code where ever possible. If platform specific is required, it MUST be guarded.

Example Listing 2.38 shows how to write platform acceptable platform specific code.

Listing 2.38 Handling of platform specific code
 1
 2import os
 3import platform
 4
 5
 6def some_function():
 7    """Just a dummy function"""
 8    if platform.uname().system.lower().startswith("win"):
 9        print("Some Windows code")
10    else:
11        print("Feature only support on windows")
12
13    path = "some/path"  # bad - works on all platforms, but no good style
14    path = "some\\path"  # bad - works only on Windows
15    path = os.path.join("some", "path")  # good - works on every platform
16    print(path)

2.3.7. wscript Specific rules (PYTHON:007)

includes and source or might be less readable if they are split over multiple lines (as black would format it like this on default). Therefore includes and source might be written as follows, if it increases readability:

Listing 2.39 Format includes in wscript
 1
 2import os
 3
 4
 5def build(bld):
 6    """builds something..."""
 7    # fmt: off
 8    # pylint: disable=line-too-long
 9    includes = [
10        # ...
11        os.path.join("..", "..", "os", "freertos"),
12        os.path.join("..", "..", "os", "freertos", "include"),
13        os.path.join("..", "..", "os", "freertos", "portable", "ccs", "arm_cortex-r5"),
14        # ...
15    ]
16    # pylint: enable=line-too-long
17    # fmt: on
  • # fmt: off disables black on formatting starting from that line and # pylint: disable=line-too-long disables the pylint error message starting from that line.

  • # fmt: on re-activates black on formatting starting from that line and # pylint: enable=line-too-long re-activates the pylint error message starting from that line.