diff --git a/_comments_docstrings.qmd b/_comments_docstrings.qmd index bbece53..262a16b 100644 --- a/_comments_docstrings.qmd +++ b/_comments_docstrings.qmd @@ -51,8 +51,6 @@ Cat code comment image by [35_equal_W](https://www.reddit.com/r/ProgrammerHumor/ ## Comments - some thoughts^[Adapted from [@stackoverflow_comments]] {.smaller} -::: {.incremental} - - Comments should not duplicate the code. - Good comments do not excuse unclear code. - Comments should dispel confusion, not cause it. @@ -65,8 +63,6 @@ Cat code comment image by [35_equal_W](https://www.reddit.com/r/ProgrammerHumor/ - Comments are not documentation. - Read by developers, documentation is for... -::: - ## Docstrings {.smaller} @@ -179,6 +175,7 @@ def calculate_gyroradius(mass, v_perp, charge, B, gamma=None): ::: :::: + ## Exercise 5 {.smaller} Go to exercise 5 and examine the comments: diff --git a/_fstrings_magic_config.qmd b/_fstrings_magic_config.qmd index 1dbe3b8..8ba3b60 100644 --- a/_fstrings_magic_config.qmd +++ b/_fstrings_magic_config.qmd @@ -1,5 +1,6 @@ # Writing better (Python) code + ## Remove Magic Numbers {.smaller} @@ -133,7 +134,7 @@ def bpm(l): ::: :::: - + @@ -198,7 +199,7 @@ Magic Numbers - Look through the code and identify any magic numbers. - Implement what you feel is the best approach in each case - + ::: :::: + diff --git a/_licenses.qmd b/_licenses.qmd index d1fc922..ba68799 100644 --- a/_licenses.qmd +++ b/_licenses.qmd @@ -37,6 +37,7 @@ The above copyright notice and this permission notice shall be included in all c THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ``` + diff --git a/index.html b/index.html index bd2520e..b2e14ce 100644 --- a/index.html +++ b/index.html @@ -7433,27 +7433,25 @@

Comments to avoid

Comments - some thoughts1

-
-

Docstrings

@@ -7550,67 +7548,86 @@

Docstrings

return r_g +
-
-

Docstrings - pydocstyle

-
-
-

pydocstyle is a tool we can use to help ensure the quality of our docstrings.1

-
-
(myvenv) $ pip install pydocstyle
-(myvenv) $ pydocstyle myfile.py
-(myvenv) $ pydocstyle mydirectory/
-(myvenv) $
-(myvenv) $
-(myvenv) $ pydocstyle gyroradius.py
-gyroradius.py:2 in public function `calculate_gyroradius`:
-        D202: No blank lines allowed after function docstring (found 1)
-gyroradius.py:2 in public function `calculate_gyroradius`:
-        D400: First line should end with a period (not 'd')
-gyroradius.py:2 in public function `calculate_gyroradius`:
-        D401: First line should be in imperative mood (perhaps 'Calculate', not 'Calculates')
-(myvenv) $
-
-

Note: pydocstyle does not catch missing variables in docstrings. This can be done with Pylint’s docparams and docstyle extensions but is left as an exercise to the reader.

-
-
-
def calculate_gyroradius(mass, v_perp, charge, B, gamma=None):
-    """
-    Calculates the gyroradius of a charged particle in a magnetic field
-
-    Parameters
-    ----------
-    mass : float
-        The mass of the particle [kg]
-    v_perp : float
-        velocity perpendicular to magnetic field [m/s]
-    charge : float
-        particle charge [coulombs]
-    B : float
-        Magnetic field strength [teslas]
-    gamma : float, optional
-        Lorentz factor for relativistic case. default=None for non-relativistic case.
-
-    Returns
-    -------
-    r_g : float
-        Gyroradius of particle [m]
-
-    Notes
-    -----
-    .. [1]  Walt, M, "Introduction to Geomagnetically Trapped Radiation,"
-       Cambridge Atmospheric and Space Science Series, equation (2.4), 2005.
-    """
-
-    r_g = mass * v_perp / (abs(charge) * B)
-
-    if gamma:
-        r_g = r_g * gamma
-
-    return r_g
-
-
-

Exercise 5

Go to exercise 5 and examine the comments:

@@ -7713,40 +7730,51 @@

Example: MIT License

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -
-
-

Add a license in Github

+ -
+

Writing better (Python) code

+

Remove Magic Numbers

@@ -7772,108 +7800,124 @@

Remove Magic Numbers

-
"""Module implementing pendulum equations."""
-import numpy as np
-
-def get_period(l):
-    """..."""
-    return 2.0 * np.pi * np.sqrt(l / 9.81)
-
-def max_height(l, theta):
-    """..."""
-    return l * np.cos(theta)
-
-def max_speed(l, theta):
-    """..."""
-    return np.sqrt(2.0 * 9.81 * max_height(l, theta))
-
-def energy(m, l, theta):
-    """..."""
-    return m * 9.81 * max_height(l, theta)
-
-def check_small_angle(theta):
-    """..."""
-    if theta <= np.pi / 1800.0:
-        return True
-    return False
-
-def bpm(l):
-    """..."""
-    return 60.0 / get_period(l)
-
-
-
+
"""Module implementing pendulum equations."""
+import numpy as np
+
+def get_period(l):
+    """..."""
+    return 2.0 * np.pi * np.sqrt(l / 9.81)
+
+def max_height(l, theta):
+    """..."""
+    return l * np.cos(theta)
+
+def max_speed(l, theta):
+    """..."""
+    return np.sqrt(2.0 * 9.81 * max_height(l, theta))
+
+def energy(m, l, theta):
+    """..."""
+    return m * 9.81 * max_height(l, theta)
+
+def check_small_angle(theta):
+    """..."""
+    if theta <= np.pi / 1800.0:
+        return True
+    return False
+
+def bpm(l):
+    """..."""
+    return 60.0 / get_period(l)
+
+
+
-
"""Module implementing pendulum equations."""
-import numpy as np
-
-GRAV = 9.81
-
-def get_period(l):
-    """..."""
-    return 2.0 * np.pi * np.sqrt(l / GRAV)
-
-def max_height(l, theta):
-    """..."""
-    return l * np.cos(theta)
-
-def max_speed(l, theta):
-    """..."""
-    return np.sqrt(2.0 * GRAV * max_height(l, theta))
-
-def energy(m, l, theta):
-    """..."""
-    return m * GRAV * max_height(l, theta)
-
-def check_small_angle(theta, small_ang=np.pi/1800.0):
-    """..."""
-    if theta <= small_ang:
-        return True
-    return False
-
-def bpm(l):
-    """..."""
-    # Divide 60 seconds by period [s] for beats per minute
-    return 60.0 / get_period(l)
+
"""Module implementing pendulum equations."""
+import numpy as np
+
+GRAV = 9.81
+
+def get_period(l):
+    """..."""
+    return 2.0 * np.pi * np.sqrt(l / GRAV)
+
+def max_height(l, theta):
+    """..."""
+    return l * np.cos(theta)
+
+def max_speed(l, theta):
+    """..."""
+    return np.sqrt(2.0 * GRAV * max_height(l, theta))
+
+def energy(m, l, theta):
+    """..."""
+    return m * GRAV * max_height(l, theta)
+
+def check_small_angle(theta, small_ang=np.pi/1800.0):
+    """..."""
+    if theta <= small_ang:
+        return True
+    return False
+
+def bpm(l):
+    """..."""
+    # Divide 60 seconds by period [s] for beats per minute
+    return 60.0 / get_period(l)
-
-
-

Put config in a config file

-
-
-
    -
  • Ideally we shouldn’t have hop in and out of the code (and recompile in higher level langs) every time we change a runtime setting
  • -
  • No easy record of runs
  • -
-

Instead:

-
    -
  • It’s easy to read a json file into python as a dictionary Handle as you wish - create a class, read to variables etc.
  • -
  • Could even make config filename a command line argument
  • -
-
-
{
-  "config_name": "June 2022 m01 n19 run",
-  "start_date": "2022-05-28 00:00:00",
-  "end_date": "2022-06-12 23:59:59",
-  "satellites": ["m01", "n19"],
-  "noise_floor": [3.0, 3.0, 3.0],
-  "check_SNR": true,
-  "L_lim": [1.5, 8.0],
-  "telescopes": [90],
-  "n_bins": 27
-}
-
import json
-
-
-with open('config.json') as json_file:
-    config = json.load(json_file)
-
-print(config)
-
{'config_name': 'June 2022 m01 n19 run', 'start_date': '2022-05-28 00:00:00', 'end_date': '2022-06-12 23:59:59', 'satellites': ['m01', 'n19'], 'noise_floor': [3.0, 3.0, 3.0], 'check_SNR': True, 'L_lim': [1.5, 8.0], 'telescopes': [90], 'n_bins': 27}
-
+
@@ -7885,21 +7929,22 @@

Exercise 6

  • Look through the code and identify any magic numbers.
  • Implement what you feel is the best approach in each case
  • -

    f-strings

    - -
    -

    Configuration settings

    -
      -
    • There is helpfully a list of configurable inputs at the end of the file under "__main__".
      -We can improve on this, however, by placing them in a configuration file.
    • -
    • Create an appropriate json file to be read in as a dictionary and passed to the main function.
    • -
    +
    @@ -7923,7 +7968,7 @@

    Other things

  • Type checking with mypy
  • -

    These lessons will be added to the course content in future but are beyond the scope of today.

    +

    These lessons are beyond the scope of today.