0 Introduction

The goal of this blog is to help me build a code with the following high quality:

  • Clear structure
  • Clean code format
  • Consistent code style
  • High readability
  • Good usability
  • Robust Verifiability
  • High Reliability
  • Good Extensibility
  • Well Maintainability

1 General Style Guide

To introduce more about our project style guide, we will introduce some general style guide, since our project style guide is built on top of these. So these knowledge are useful for going deeper.

And in this blog, I will just summarize some most common knowledge but not listing all the style guide details. For more details, please refer to [1] [2] [3].

There some common coding naming styles that will be used in our projects:

1.1 Camel Case

  • Words are written without spaces.
  • Each word, except the first one, begins with a capital letter.
  • Example: myVariableName, calculateSquareRoot

1.2 Pascal Case (or Upper Camel Case)

  • Similar to Camel Case, but the first word also starts with a capital letter.
  • Often used for class names and type names.
  • Example: MyClassName, EmployeeDetails.

1.3 Snake Case

  • Words are separated by underscores (_) and are all lowercase.
  • Often used for variable names, function names, and file names.
  • Example: my_variable_name, calculate_square_root.

1.4 UPPER CASE (or SCREAMING SNAKE CASE)

  • All letters are in uppercase.
  • Words are separated by underscores (_).
  • Often used for constants and global variables.
  • Example: MAX_VALUE, CONFIG_FILE_NAME.

2 Python Style Guide

2.1 Check tools

There several handy style check tools we recommend.

Please note that from a quality check standpoint: flake8 < YAPF < pylint.

Your code should pass at least flake8 check, and we recommend you to use pylint to maintain a higher quality standards.

2.1.1 flake8

Official Tutorial:

Introduction:

flake8 is a popular Python linting tool that is used to check Python code for compliance with coding standards and style conventions. It combines multiple tools and plugins to perform various checks on your Python code, including style checks, syntax checks, and more. flake8 is widely used in the Python development community to help ensure code quality and maintainability.

Installation:

To install flake8 :

pip install flake8

How to use:

Please use .flake8 to run flake8:

  • Download this flake8 configuration file, and put it under your project directory.

  • When you run the flake8 command, Flake8 will automatically check and use the flake8 config file .flake8 file under the root directory.

  • For example, your project root structure as follows:

    my_project/
        ├── .flake8
        ├── main.py
        ├── utils.py
    
  • Run the following command to check your code:

    flake8 main.py
    

Running examples:

The output of some flake8 check example:

  • Good one:

  • Bad one:

2.1.2 YAPF

Introduction:

YAPF (Yet Another Python Formatter) is a tool that can automatically format Python code to adhere to PEP 8 and other coding style guidelines. While YAPF is primarily used for code formatting, you can use it to check the coding style of a Python program as well by running it with specific options.

This is the tool we don’t recommend to use in our project since its coding style rules are a little bit different from us.

Installation:

To install yapf:

pip install yapf

How to use:

To check the coding style by running the following command:

yapf --diff your_code.py

Running examples:

The output of some yapf check example:

  • Good one:

  • Bad one:

2.1.3 pylint

Official Tutorial:

Introduction:

Pylint is a static code analyser for Python 2 or 3. The latest version supports Python 3.8.0 and above.

Pylint analyses your code without actually running it. It checks for errors, enforces a coding standard, looks for code smells, and can make suggestions about how the code could be refactored.

Advantages:

  • Omissions can be found, such as spelling errors, using unassigned variables, etc.

Disadvantages:

  • pylint is not perfect, some times we need to:
    • bypass it
    • suppress its warnings
    • improve it

Installation:

pip install pylint

How to use:

Please use pylintrc to run pylint:

pylint --rcfile=pylintrc your_code.py
  • Download this file pylintrc to your root directory and run the above command.

Running examples:

  • Good one:

  • Bad one:

To suppress warnings, for example, this is your code:

# pylint: disable=C0114

def add_numbers(input_a, input_b):
    """
    This function adds two numbers.

    :param a: The first number to add.
        :type a: int or float
    :param b: The second number to add.
        :type b: int or float
    :return: The sum of a and b.
        :type: int or float
    """
    output_result = input_a + input_b
    return output_result

def do_PUT(): # pylint: disable=invalid-name
    print("hello world")

def main():
    num1 = 5
    num2 = 3
    sum_result = add_numbers(num1, num2)
    print(f"The sum of {num1} and {num2} is: {sum_result}")

if __name__ == "__main__":
    main()

Before you add the following code:

# pylint: disable=C0114
# pylint: disable=invalid-name

You will see:

After you add the above two lines of code to suppress it, you will see:

2.2 Import

Reasonable import order

Considering the PEP8 standard and usage habits, we recommend that users use the following import order:

  • Standard library imports

  • Related third party imports

  • Local application/library specific imports

  • Relative imports

  • For example:

    import numpy as np
    import torch 
    import carla
    import opencda.scenario_testing.utils.sim_api as sim_api
    from opencda.core.common.cav_world import CavWorld
    

Some import rules:

  • Use import x to import packages and modules.

    import carla
    
  • Use from x import y to import specific modules, x is the package name

    from opencda.core.common.cav_world import CavWorld
    
  • In the following conditions, use from x import y as z:

    • y is too long
    • z is standard abbreviation: like np is for numpy
    • There are two modules name y
    • y is conflict with the global variables

2.3 Functions

Some rules for function:

  • Function name should be in snake case naming style:

    For example get_area:

    def get_area(input_a,input_b):
    
  • Parameters should also be in snake case naming style:

    For example: input_a,input_b

    def get_area(input_a,input_b):
    
  • Module docstring is necessary:

    Detailed description of the function: what and why

    def calculate_cosine_plus_sine(rad_x):
        """
        Calculate the sum of cosine and sine of a given angle 'x' in radians.
      
        Args:
            x (float): The angle in radians.
      
        Returns:
            float: The result of cos(x) + sin(x).
        """
        result = math.cos(rad_x) + math.sin(rad_x)
        return result
    
    • It includes the introduction/explanation of this function
    • Each element of the function need to be fully explained
      • Arguments as input
      • Returns as output

Tips:

  • You can use some handy plug-ins on VScode:

  • You can also use ChatGPT to help you if you are lazzy:

2.4 Class

Some rules for class:

  • Use Pascal Case(Upper Camel Case) to name class name:

    class BoundingBox():
    
  • Module docstring is necessary:

    class BoundingBox():
        """
        A class representing a bounding box in a 2D space.
      
        Attributes:
            x_min (float): The minimum x-coordinate of the bounding box.
            y_min (float): The minimum y-coordinate of the bounding box.
            x_max (float): The maximum x-coordinate of the bounding box.
            y_max (float): The maximum y-coordinate of the bounding box.
        """
    

2.5 Some examples

The following are some examples:

3 C++ Style Guide

3.1 Check tool: Clang-Format

There are several C/C++ language format style check tools, like Clang-format, Cppcheck, Cpp Linter. Here we just recommend Clang-format.

Introduction:

Clang-Format is a popular code formatting tool that is part of the Clang compiler project, which is a C, C++, and Objective-C compiler. Clang-Format is specifically designed to help developers and teams maintain a consistent code style and formatting across their codebase. It automates the process of formatting code according to a predefined set of rules, making the code more readable and maintainable

Installation:

  • For Linux:

    sudo apt install clang-format
    
  • For mac:

    brew install clang-format
    
  • For windows:

    Click to download here

Integration with IDE:

For vscode, search Clang-format in the extension, and the first one is what you need:

Use ctrl+shit+i to let Clang-format help you correct your code directly inside the VS Code.

How to use:

Use the default format stylem, like llvm or google by using the following command:

clang-format -style=llvm your_code.cpp
  • This will give you the modified version print out on the screen

Or you can use the following command:

clang-format -style=llvm -i your_code.cpp
  • This will change your code format directly using the clang-format

Reference

[1] https://google.github.io/styleguide/

[2] Google 开源项目风格指南

[3] PEP 8 – Style Guide for Python Code