Readable:
A human being can easily understand the purpose of the code and can maintain the code.
Reusable:
Code is written in such a way that it can be reused across multiple contexts with little or no modification required.
Robust:
A computer system is able to cope with errors during execution.
Code is read more often than it is written. — Guido van Rossum (creator of Python)
# Example 1 - very unpythonic
i = 0
my_data = []
while i < 100:
my_data += [i * i / 356]
i += 1
# Example 2 - more use of Python features, such as `range` and `append`
my_data = []
for i in range(100):
my_data.append(i**2 / 356)
Python at its best:
Style Guides can help to stay consistent
Language | Linters | Formatters |
---|---|---|
R | lintr | formatR, styler |
Python | ruff, pylint | ruff, black |
Function: lintr::lint(filename)
The lintr package in R:
The ruff
library in Python:
Function: ruff check --fix path/to/code/to/check.py
Run a linter through your code and identify style issues:
lintr
ruff check
Edit your code to improve the style compatibility, based on the feedback from your linter.
Run an autoformatter through your code to automatically fix issues instead of simply flagging them:
styler
ruff format
If you find code that is hard to read, or variable names that need adjusting, make a note to work on it. Use #TODO or another consistent label so you can extract these notes later.
Workshop Computational Reproducibility