Code Readability

Author

Neha Moopen

Published

October 26, 2022

Note

How can you make your code more readable?

👆 That’s what we discussed in this edition of the Programming Cafe. We learnt about style guides in R (the tidyverse style guide) & Python (PEP-8) and how we can use linters and (auto)formatters to ensure our code adheres to conventions followed by the community.

Slides

Exercises

The scripts for the exercises can be downloaded via this link. If more convenient, the code has also been included as chunks/blocks below.

  • Run a linter through your R and/or Python code and identify style issues.
    • Edit your code to improve the style compatibility, based on the feedback from your linter.
  • Run an (auto)formatter through your R and/or Python code to automatically fix issues instead of simply flagging them.

R

Use the lintr & styler packages to lint and (auto)format the following code:

fun <- function(one) {
  one.plus.one <- oen + 1
  four <- newVar <- matrix(1:10, nrow = 2)
  four[1, ]
  txt <- "hi"
  three <- two + 1
  if (txt == "hi") 4
  5
}

The relevant functions are:

  • lintr::lint(filename)
  • styler::style_file(filepath)

Python

Use the flake8 & black` libraries to lint and (auto)format the following code:

### This is an important function
some_constant=1
def MYFUNCTION (X ,y = 1): 
 z="1",;y=y+1
 return (
        X+y  <  some_constant) == True  #This is a very long comment that about how the condition can be checked directly in the return statement.
from numpy import *

The relevant functions are:

  • flake8 path/to/code/to/check.py
  • black {source_file_or_directory}

References

  1. https://utrechtuniversity.github.io/workshop-computational-reproducibility/chapters/readability.html