C2SM / c2sm.github.io

C2SM User Landing Page
https://c2sm.github.io/
MIT License
0 stars 1 forks source link

add info about code formatting, linting, checkers to coding best practises #105

Open ruthlorenz opened 9 months ago

ruthlorenz commented 9 months ago

flake8, black, isort.... @mathause will help review

mathause commented 9 months ago

TODO: double check!

option 1 - ruff

  1. installation

    mamba install -c conda-forge ruff
  2. Add (or update) a pyproject.toml file in the root of the project:

    
    [tool.ruff]
    
    [tool.ruff.lint]
    # E402: module level import not at top of file
    # E501: line too long - let the formatter worry about this
    # E731: do not assign a lambda expression, use a def
    ignore = [
     "E402",
     "E501",
     "E731",
    ]
    select = [
     "F", # Pyflakes
     "E", # Pycodestyle
     "W", # warnings
     "I", # isort
     "UP", # Pyupgrade
    ]
    
  3. run the tool

    Only the "checker"

    ruff check --fix .

    Only the formatter:

    ruff format .

    Or both at once:

    ruff check --fix .; ruff format .
  4. Comments:

    • maybe leave away the --fix option first to see what will happen
    • you will probably have to do some changes to your code to make the tool happy (it will e.g. point out variables that are never used)
    • Inline lines with code and inline comments will probably not look good -> move the comments on a separate line. For example

      if feature > threshold: # the threshold is arbitrary and several should be tested to check stability
        pass

      would be reformatted to

      if (
        feature > threshold
      ):  # the threshold is arbitrary and several should be tested to check stability
        pass

      so it's better to manually change to

      # the threshold is arbitrary and several should be tested to check stability
      if feature > threshold:
        pass

Option 2 - isort, black, and flake8

installation ```bash mamba install -c conda-forge isort black tokenize-rt ipython ``` (or `python -m pip install isort black[jupyter] ipthon`) configuration in `setup.cfg` at the root of the project ```cfg [flake8] ignore= # E203: whitespace before ':' - doesn't work well with black # E402: module level import not at top of file # E501: line too long - let black worry about that # E731: do not assign a lambda expression, use a def # W503: line break before binary operator E203, E402, E501, E731, W503 exclude= build docs .git [isort] profile = black skip_gitignore = true force_to_top = true ``` running: the order is important (black needs to be after isort and the checker needs to be last) ```bash isort .; black .; flake8 .; ```

edit: since version 0.6 ruff also checks notebooks