spacetelescope / style-guides

An opinionated guide on how we work.
Creative Commons Attribution 4.0 International
55 stars 33 forks source link

Guideline for repeated code block in Jupyter notebook #45

Open pllim opened 6 years ago

pllim commented 6 years ago

Something brought up by @samanthalh -- When one is developing notebook for users and find oneself in a situation where one needs to copy and paste the same code with slight variations (e.g., plotting results of subsequent tweakreg runs on the same dataset), is it better to:

  1. Brute force copy and paste; OR
  2. Write a function of the repeated code and then call it with different inputs where they vary?

Brute force way is more tedious and provides clarity and possibly is resistant to out-of-order cell runs in some cases. A function might be more elegant and reduce future maintenance but user needs to scroll up to see what happens in the function, and the cell with the function needs to be run before all the other stuff.

Is a guide line for such a thing within scope of this document?

hcferguson commented 6 years ago

It's a common quandary. My preference would be to define each function in a cell of its own with if it's more than a few lines long, since otherwise all that repeated code can just obfuscate the examples being communicated in the later cells. As a matter of style, I'd suggest these be collected in their own section early in the notebook, and descriptions of what they do in separate markdown cells.