Skip to content

Commit

Permalink
some tidying and resolving warnings and errors
Browse files Browse the repository at this point in the history
  • Loading branch information
sneakers-the-rat authored and lwasser committed Oct 22, 2024
1 parent 979d94a commit 1b20f37
Show file tree
Hide file tree
Showing 12 changed files with 59 additions and 35 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/build-book.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ jobs:
run: python3 -m pip install nox

- name: Build book
run: nox -s docs
run: nox -s docs-test

# Save html as artifact for CircleCI viewing
- name: Save book html as artifact for viewing
Expand Down
12 changes: 8 additions & 4 deletions clean-modular-code/activity-3/clean-code-activity-3.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ kernelspec:
(clean-code-activity-3)=
# Activity 3: Tests & Checks for your code

* In [activity 1](../activity-1/clean-code-activity-1), you made your code cleaner and more usable using [expressive variable names](python-expressive) and docstrings to document the module.
* In [activity 2](../activity-2/clean-code-activity-2), you made your code more DRY ("Don't Repeat Yourself") using [functions](write-functions) and [conditionals](python-conditionals).
* In [activity 1](../activity-1/clean-code-activity-1), you made your code cleaner and more usable using [expressive variable names](python-expressive-code) and docstrings to document the module.
* In [activity 2](../activity-2/clean-code-activity-2), you made your code more DRY ("Don't Repeat Yourself") using [functions](write-functions) and [conditionals](conditionals).

In this activity, you will build checks into your workflow using [try/except](try-except) blocks added to functions to handle some "features" found in the JOSS, CrossRef citation data.

Expand All @@ -39,9 +39,9 @@ Writing robust code that handles unexpected values will make your code run smoot

There are several strategies that you can employ to handle unusual data values. In this activity, you will apply the following strategies to make your code more robust, maintainable & usable:

* **[conditional statements](../checks-conditionals/python-conditionals)**
* **[conditional statements](../../code-workflow-logic/python-conditionals)**
to check for specific conditions before executing code. This allows you to create different pathways for code to execute based on specific conditions.
* **[Try/except blocks](../checks-conditionals/python-function-checks)** allow
* **[Try/except blocks](../../code-workflow-logic/python-function-checks)** allow
you to handle potential errors by attempting an operation and catching any
exceptions if they occur, providing useful feedback.Sometimses, you may want the program to end on an error. In other cases, you may want to handle it in a specific way.
* **[Fail fast with useful error messages](fail-fast)**: Failing fast is a software engineering term that means allowing your
Expand Down Expand Up @@ -445,6 +445,7 @@ def clean_title(title):
editable: true
slideshow:
slide_type: ''
tags: [raises-exception]
---
# Add checks to the clean_title function to make sure this code runs
all_titles = []
Expand Down Expand Up @@ -491,6 +492,7 @@ print(type(joss_pubs_df["title"][0][0]))
editable: true
slideshow:
slide_type: ''
tags: [raises-exception]
---
print(f"The value is {joss_pubs_df['title'][0]}")
get_title(joss_pubs_df["title"][0])
Expand All @@ -501,6 +503,7 @@ get_title(joss_pubs_df["title"][0])
editable: true
slideshow:
slide_type: ''
tags: [raises-exception]
---
clean_title(joss_pubs_df["title"][1])
```
Expand Down Expand Up @@ -529,6 +532,7 @@ workflow below so it runs. To do this you can use the results of the functions t
editable: true
slideshow:
slide_type: ''
tags: [raises-exception]
---
# Full code snippet
import json
Expand Down
12 changes: 1 addition & 11 deletions clean-modular-code/intro-clean-code.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,19 +33,9 @@ Intro <self>
Python Code Style <python-pep-8>
Don't Repeat Yourself <python-dry-modular-code>
Expressive Code <python-expressive-code>
Write Pseudocode <write-pseudocode>
:::

:::{toctree}
:hidden:
:caption: Functions, Conditionals & Checks
:maxdepth: 2

Conditional statements <checks-conditionals/python-conditionals>
Functions <checks-conditionals/about-python-functions>
Functions <checks-conditionals/write-python-functions>
Function checks <checks-conditionals/python-function-checks>
Function Tests & Checks <checks-conditionals/python-common-exceptions>
:::


:::{toctree}
Expand Down
6 changes: 3 additions & 3 deletions clean-modular-code/write-pseudocode.md
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ if paper_1["citations"]:
print({
"title": paper_1["title"][0],
"pub_date": pub_date_1,
"citations": citations_1
"citations": avg_citations_1
})
# Paper 2
Expand All @@ -158,7 +158,7 @@ if paper_2["citations"]:
print({
"title": paper_2["title"][0],
"pub_date": pub_date_2,
"citations": citations_2
"citations": avg_citations_2
})
# Paper 3
Expand All @@ -169,7 +169,7 @@ if paper_3["citations"]:
print({
"title": paper_3["title"][0],
"pub_date": pub_date_3,
"citations": citations_3
"citations": avg_citations_3
})
```

Expand Down
14 changes: 14 additions & 0 deletions code-workflow-logic/about-python-functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,20 @@ jupyter:
name: python3
---

:::{toctree}
:hidden:
:maxdepth: 2

About Python Functions <self>
write-python-functions
python-function-checks
python-functions-multi-parameters
python-conditionals
python-conditionals2
python-common-exceptions
:::


<!-- #region editable=true slideshow={"slide_type": ""} -->
(about-functions)=
# Why write functions?
Expand Down
2 changes: 1 addition & 1 deletion code-workflow-logic/python-conditionals.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ jupyter:
name: python3
---

(python-conditionals)=
(conditionals)=
# Conditional statements in Python

While there are many strategies for improving efficiency and removing repetition in code, three commonly used DRY strategies are conditional statements, loops, and functions.
Expand Down
12 changes: 9 additions & 3 deletions code-workflow-logic/python-function-checks.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ kernelspec:
# Write Flexible Functions to Handle Messy Data

When working with messy or unpredictable data, your goal is to write robust code to handle the unexpected. It's important to catch errors early
and handle them gracefully. [Using functions](python-functions) is a great first step in creating
and handle them gracefully. [Using functions](about-functions) is a great first step in creating
a maintainable and resilient data processing workflow. Functions provide modular
units that can be tested independently, making handling edge cases
and unexpected scenarios easier.
Expand Down Expand Up @@ -48,10 +48,13 @@ print(clean_title(["hi, i'm a title"]))
print(clean_title("hi, i'm a title"))
```

The function below uses [conditional statements](python-conditionals) to check the input provided by the user. It uses a "look before you leap" approach to check to see if the input is provided in a list format.
The function below uses [conditional statements](conditionals) to check the input provided by the user. It uses a "look before you leap" approach to check to see if the input is provided in a list format.
If it isn't, it returns the title in its provided format.

```{code-cell} ipython3
---
tags: [raises-exception]
---
def clean_title(title):
"""This function checks explicitly to see if it is provided with a value that is a list. It then
makes a decision about how to process the function input based on
Expand Down Expand Up @@ -212,7 +215,7 @@ file_data = read_file("nonexistent_file.txt")

You could anticipate a user providing a bad file path. This might be especailly possible if you plan to share your code with others and run it on different computers and different operating systems.

In the example below, you use a [conditional statement](python-conditionals) to check if the file exists; if it doesn't, it returns None. In this case, the code will fail quietly, and the user will not understand that there is an error.
In the example below, you use a [conditional statement](conditionals) to check if the file exists; if it doesn't, it returns None. In this case, the code will fail quietly, and the user will not understand that there is an error.

This is also dangerous territory for a user who may not understand why the code runs but doesn't work.

Expand Down Expand Up @@ -275,6 +278,9 @@ If you wanted to provide less information to the user, you could use `from None`
only return the exception information related to the error that you handle within the try/except block.

```{code-cell} ipython3
---
tags: [raises-exception]
---
def read_file(file_path):
try:
with open(file_path, 'r') as file:
Expand Down
4 changes: 2 additions & 2 deletions code-workflow-logic/python-functions-multi-parameters.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ jupyter:
---

<!-- #region -->
[multi-parameter-functions)=
# Write mmulti parameter functions
(multi-parameter-functions)=
# Write Multi-Parameter Functions

##Learning Objectives

Expand Down
11 changes: 6 additions & 5 deletions code-workflow-logic/write-python-functions.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
---
layout: single
title: 'Write Python Functions: Modular Code'
excerpt: "A function is a reusable block of code that performs a specific task. Learn how to write functions in Python to eliminate repetition and improve efficiency in your code."
last_modified: '{:%Y-%m-%d}'.format(datetime.now())
excerpt: |
A function is a reusable block of code that performs a specific task. Learn how to write functions in Python to eliminate repetition and improve efficiency in your code.
last_modified: '{:%Y-%m-%d}'
jupyter:
jupytext:
formats: ipynb,md
Expand All @@ -18,7 +19,7 @@ jupyter:
---

(write-functions)=
## How to write a Python function
# How to write a Python function

:::{tip}
## What you will learn
Expand All @@ -28,13 +29,13 @@ jupyter:

To define a function in Python, you need:
- The `def` keyword to start the function definition.
- A function name that follows [PEP 8 guidelines](../python-expressive-code.md) for naming.
- A function name that follows [PEP 8 guidelines](../clean-modular-code/python-expressive-code.md) for naming.
- Input parameters (optional), defined inside parentheses `()`.
- A `return` statement that specifies the output of the function.
- A docstring that explains what the function does and defines the function's inputs and outputs. We suggest that you use numpy style docstrings for scientific Python code.
-

### An example Python function
## An example Python function

An example Python function with two input variables is below:

Expand Down
3 changes: 2 additions & 1 deletion conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@
},
# Increase this as lessons are added -
# set low to hide links to other pyos sites and allow nav between lessons
"header_links_before_dropdown": 2,
"header_links_before_dropdown": 3,
"use_edit_page_button": True,
"show_nav_level": 2,
"navigation_depth": 3,
Expand Down Expand Up @@ -144,6 +144,7 @@
"**/data/**",
"_law_tests",
"**/*.ipynb", # we use myst notebooks for publishing
"venv",
]

# For sitemap generation
Expand Down
14 changes: 11 additions & 3 deletions index.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
* [Write Python Functions](write-functions)
* [Add checks to functions](functions-checks)
* [Multi parameter functions](multi-parameter-functions)
* [Write Conditionals to redirect code](python-conditionals)
* [Write Conditionals to redirect code](conditionals)
* [Common Python exceptions ](common-exceptions)

<!--
Expand Down Expand Up @@ -61,15 +61,23 @@ These lessons help scientists understand best practices and tools used in the Py

:::{toctree}
:hidden:
:caption: Lessons
:caption: Clean Code
:maxdepth: 2

Clean Code <clean-modular-code/intro-clean-code>
:::

:::{toctree}
:hidden:
:caption: Lessons
:caption: Code Checks
:maxdepth: 2

Code Checks <code-workflow-logic/about-python-functions>
:::

:::{toctree}
:hidden:
:caption: Publish Code
:maxdepth: 2

Publish Code <publish-share-code/intro>
Expand Down
2 changes: 1 addition & 1 deletion publish-share-code/share-code-github.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ Hosting code on GitHub helps you manage your projects, track changes, and keep y

## Cite your code

Even if you haven't published your code in an academic Journal, you can create a DOI that allows you to cite it using [Zenodo](zendo). While you can upload code and other types of documents to Zenodo at any time, if you are using GitHub, you can create a direct connection, which will not only provide a DOI for the GitHub repository but also allow you to create new sub-DOIs for every new version of your code that you make.
Even if you haven't published your code in an academic Journal, you can create a DOI that allows you to cite it using [Zenodo](zenodo). While you can upload code and other types of documents to Zenodo at any time, if you are using GitHub, you can create a direct connection, which will not only provide a DOI for the GitHub repository but also allow you to create new sub-DOIs for every new version of your code that you make.


<!--
Expand Down

0 comments on commit 1b20f37

Please sign in to comment.