From 87548d52ad9711b474ee3c24e0d5f5caf43a1e4b Mon Sep 17 00:00:00 2001 From: Leah Wasser Date: Mon, 7 Oct 2024 15:17:32 -0600 Subject: [PATCH 01/18] fix: edits to pep 8 page --- clean-modular-code/python-pep-8.md | 108 ++++++++++++++++------------- 1 file changed, 61 insertions(+), 47 deletions(-) diff --git a/clean-modular-code/python-pep-8.md b/clean-modular-code/python-pep-8.md index e5a8a68..f9e6504 100644 --- a/clean-modular-code/python-pep-8.md +++ b/clean-modular-code/python-pep-8.md @@ -16,10 +16,10 @@ kernelspec: # Use PEP 8 To Write Easier-to-Read Code -:::{admonition} Learning Objectives +:::{admonition} What you will learn :class: tip -* Describe the benefits of using code standards. +* Describe the benefits of using code styles guides. * Explain the PEP 8 style guide and how it helps promote code readability. * Describe key components of the PEP 8 style guide, including naming conventions and white space. * List tools to help you apply the PEP 8 style guide to your code. @@ -28,13 +28,13 @@ kernelspec: ## What is Python PEP 8 code style? -Code syntax standards refer to rules associated with how code is formatted. These rules can including things like: +Code syntax standards refer to rules associated with how code is formatted. These rules include things like: * How to space code elements in a script, * How to format and create comments, and -* Naming conventions for variables, functions and classes +* Naming conventions for variables, functions, and classes -## Why Use Code Standards When Writing Python Code +## Why use code standards when writing Python code Code standards help make your code more readable. Consider this page that you are reading right now. Some conventions are followed that most of us are familiar with (but may not even think about). These conventions include: @@ -47,33 +47,35 @@ These conventions lead to text that you can read easily, like this: `This is a sentence. And another sentence with a Name and a location like Florida, USA.` -Now imagine reading a book that has no spacing, no capitalization and didn't follow the regular English language writing conventions that you know. This book would become increasingly hard to read. For example have a look at the example below: +Now imagine reading a book with no spacing, no capitalization and that doesn't follow the regular English language writing conventions. This book would be difficult to read. Take the example below: `this is a sentence.and another sentence with a name.this text could go on forever. whatwouldhappenifweneverusedspaces?` -Code standards, just like any other language standard, are designed to make code easier to understand. +Code style standards, just like any other language standard, are designed to make code easier to read and understand. Below, you will learn about the PEP 8 standard for the **Python** scientific programming language. This is the standard used by many **Python** users. -## About the PEP 8 Standard for Python +## About the PEP 8 standard for Python PEP 8 is the style guide that is widely used in the **Python** community. This guide includes rules about naming objects, spacing rules and even how the code is laid out. -**Python** is developed and maintained by an open source community, and thus, it is not really possible to enforce the standard in mandatory way. Rather, community members choose to adhere to PEP 8 recommendations whenever possible, so that they can contribute code that can easily be read and used by the greater community of users. +**Python** is developed and maintained by an open source community, and thus, it is not possible to make code standards mandatory. Rather, community members choose to adopt PEP 8 recommendations whenever possible to contribute code that can easily be read and used by the greater community of users. -PEP 8 covers many aspects of code readability including: +PEP 8 covers many aspects of code readability, including: * naming conventions * use of comments * line lengths * use of white space -## PEP 8 Naming Conventions +## PEP 8 naming conventions The text in this section is summarized from the PEP 8 Style Guide published by the Python Software Foundation. -### Naming Convention Terminology Review +:::{tip} + +**Terminology Teview** First, let's review some terminology associated with naming conventions. @@ -97,25 +99,27 @@ First, let's review some terminology associated with naming conventions. * **Capitalized_Words_With_Underscores:** This approach is not recommended. Use one convention and stick with it. -### Name Variables Using snake_case And All Lower Case +::: -In general, it is recommended that you keep naming conventions standard in your code. We suggest a convention that uses **snake_case** and all lowercase letters in your code for variable and function names. +### Use snake_case and all lower case for variable names -``` +It is recommended that you use standard naming conventions in your code. We suggest that you use **snake_case** and all lowercase letters in your code for variable and function names. Like this: + +```python variable_one variable_two ``` -### Name Classes Using CamelCase or CapsCase +### Use CamelCase or CapsCase for class names -While regular variables and functions should use snake_case, PEP 8 +While regular variables and functions should use **snake_case**, PEP 8 suggests that you use `CamelCase` for class definitions. -``` +```python class PlotBasicObject(object): ``` -### Avoid Using Single Character Letters That Could Be Confused with Numbers +### Avoid using single character letters that could be confused with numbers Avoid using the characters: @@ -123,34 +127,34 @@ Avoid using the characters: * 'O' (uppercase letter oh), or * 'I' (uppercase letter eye) -as single character variable names. +as single-character variable names. These characters can be difficult to distinguish from numbers when using certain font families. -For example, the letter `l` can sometimes look a lot like the number `1`. If you need to use the letter `l` as a variable (this is not suggested!), considering user an uppercase letter instead. +For example, the letter `l` looks similar to the number `1`. -## Python PEP 8 Documentation Standards for Comments +## Comments and PEP 8 Documentation is an important part of writing great code. Below are some of the important PEP 8 conventions associated with documentation. -### 1. Python Comments Should Have a Space After the `#` Sign with the First Word Capitalized +### 1. Python comments should have a space after the `#` sign with the first word capitalized -Following the PEP8 style guide, single line comments should +Following the PEP8 style guide, single-line comments should start with the `#` sign followed by a space. The first word of the comment should be capitalized. Like this: `# This is a PEP 8 conforming comment` -The comment below does NOT conform to PEP8 standards +The comment below does NOT conform to PEP 8 standards `#this comment does not conform to PEP 8 standards` -### 2. Multi-line comments Used in Functions (docstrings) Should Have a Short Single Line Description Followed By More Text +### 2. Multi-line function comments (docstrings) Multi-line comments are most commonly used when creating docstrings. A docstring is the text that follows a function definition. This text helps you or someone using a function understand what the function does. -Following the PEP8 style guide, you create a function docstring using three quotes `"""`. The first line or text following the quotes should be a short, concise description of what the function does. +Following the PEP8 style guide, you create a function docstring using three quotes `"""`. The first line of text following the quotes should be a short, concise description of what the function does. Below that, you can add as much text as you'd like that provides more detail about what the function does. @@ -171,20 +175,20 @@ return the_total_sum ## Line Length -PEP 8 guidelines suggest that each line of code (as well as comment lines) should be 79 characters wide or less. This is a common standard used in other languages, including **R**. +PEP 8 guidelines suggest that both code and comment lines should all be 79 characters wide (or less). This standard is common in other languages, such as **R**. :::{tip} Most text editors allow you to set up guides to see how long your code is. You can then use these guides to create line breaks in your code. ::: -## Python PEP 8 Rules for White Space +## Python PEP 8 rules for white space Some of the white space rules have already been discussed above. These including adding a single space after a comment `# Comment here`. There are also rules associated with spacing throughout your code. These include: -* **Add blank line before a single line comment (unless it is the first line of a cell in Jupyter Notebook)** Blank lines help to visually break up code. Consider reading this page, if all of the text was mashed together in one long paragraph, it would be more difficult to read. However, when you break the text up into related paragraphs, it becomes a lot easier to read. +* **Add a blank line before a single-line comment (unless it is the first line of a cell in Jupyter Notebook)** Blank lines help to break up code visually . Consider reading this page: If all of the text was mashed together in one long paragraph, it would be more difficult to read. However, when you break the text up into related paragraphs, it becomes a lot easier to read. ```python @@ -194,8 +198,8 @@ b = 3+4 c = a+b # Read in and plot some -precip_timeseries = pd.readcsv("precip-2019.csv") -precip_timeseries.plot() +review_timeseries = pd.readcsv("pyos-data.csv") +review_timeseries.plot() ``` The code below is more difficult to read as the spacing does not break up the text. @@ -205,7 +209,7 @@ The code below is more difficult to read as the spacing does not break up the te a=1+2 b=3+4 c=a+b -data=pd.readcsv("precip-2019.csv") +data=pd.readcsv("pyos-data.csv") data.plot() ``` @@ -214,7 +218,7 @@ code becomes even more important when you start working in Jupyter Notebooks whi ```python # Process some data here -data=pd.readcsv("precip-2019.csv") +data=pd.readcsv("pyos-data.csv") # Plot data - notice how separating code into sections makes it easier to read fig, ax = plot.subplots() @@ -224,27 +228,37 @@ plt.show() ## Summary -- PEP 8 and Python -The text above provides a broad overview of some of the PEP 8 guidelines and conventions for writing **Python** code. It is not fully inclusive all of all the standards which are included in the full, online PEP 8 documentation. +The text above provides a broad overview of some of the PEP 8 guidelines and conventions for writing **Python** code. -## Tools For Applying PEP 8 Formatting To Your Code +:::{important} +This page is not fully inclusive of all of the PEP 8 standards. +::: -There are many different tools that can help you write code that is PEP 8 compliant. A tool that checks the format of your code is called a linter. -Some linters will reformat your code for you to match the standards. These include tools like Black. Or the autopep8 tool for Jupyter Notebook. ++++ -Other linters will simply check your code and tell you if things need to be fixed. A few **Python** packages that perform linting are listed below. +## Tools for applying PEP 8 format to your code -* pep8, a `Python` package that can help you check your code for adherence to the PEP 8 style guide. -* autopep8, another `Python` package that can be used to modify files to the PEP 8 style guide. +Many different tools can help you write code that is PEP 8 compliant. A tool that checks the format of your code is called a linter. -`Python` community members expect that your code will adhere to the PEP 8 standard, and if it does not, they generally will not be shy to tell you that your code is not "Pythonic"! +Some linters will reformat your code so that it matches the standards. -+++ {"editable": true, "slideshow": {"slide_type": ""}} +* [Black](https://black.readthedocs.io/en/stable/) has been a popular tool in the scientific Python ecosystem for several years. +* More recently, many people are moving to [ruff which now provides Jupyter support.](https://docs.astral.sh/ruff/configuration/#jupyter-notebook-discovery). Ruff is a perfect tool for you to use if you are developing your code in `.py` files. + + +:::{note} +Ruff doesn't currently work well with Jupyter / JupyText and myst markdown notebooks. But it can be easily configured into a .precommit workflow, which is used alongside Git and GitHub and will be applied every time you make a commit to a GitHub repo. +:::: -## Additional Resources +The pyOpenSci community has been slowly adopting Ruff because it can run many code formatters with a single configuration file, making it a convenient and easy-to-use tool. -* The PEP 8 Style Guide +:::{admonition} Linter vs. code formatter +:class: tip + +A code formatter is a tool that helps you modify your code to follow code standards. A linter checks your code and tells you if things need to be fixed, but it generally won't fix them for you. -* How To Write Beautiful Python Code with PEP 8 +Ruff is both a linter and code formatter which is why we like to use it when developing both software and .py file based workflows. +::: -* The Hitchhiker's Guide to Python by Tanya Schlusser and Kenneth Reitz ++++ {"editable": true, "slideshow": {"slide_type": ""}} From 05d9bd0406c088bd27af2529f57d12d6e166495f Mon Sep 17 00:00:00 2001 From: Leah Wasser Date: Mon, 7 Oct 2024 15:26:41 -0600 Subject: [PATCH 02/18] feat: pep 8 page --- clean-modular-code/pep8-package-imports.md | 79 ---------------------- clean-modular-code/python-pep-8.md | 66 ++++++++++++++++++ 2 files changed, 66 insertions(+), 79 deletions(-) delete mode 100644 clean-modular-code/pep8-package-imports.md diff --git a/clean-modular-code/pep8-package-imports.md b/clean-modular-code/pep8-package-imports.md deleted file mode 100644 index 5807ba7..0000000 --- a/clean-modular-code/pep8-package-imports.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -jupytext: - text_representation: - extension: .md - format_name: myst - format_version: 0.13 - jupytext_version: 1.16.4 -kernelspec: - display_name: Python 3 (ipykernel) - language: python - name: python3 ---- - -+++ {"editable": true, "slideshow": {"slide_type": ""}} - -# Best Practices for Importing Python Packages In Scientific Code - -There are a set of best practices that you should follow when importing **Python** packages in your code. These best practices are outlined in the PEP 8 guidelines and apply to both **Python** scripts and to working in **Jupyter Notebook** files. - -## Import Python Libraries at the Top of Your Script or Notebook - -It is good practice to import all of the packages that you will need at the top of your **Python** script (.py file) or in the first code cell of a **Jupyter Notebook** file. - -This allows anyone looking at your code to immediately know what packages they need to have installed in order to successfully run the code. This rule also follows the PEP 8 conventions for **Python** code. - -```python -import os - -import pandas as pd -import numpy as np -``` - -Once you have imported all of the packages that you need to run your code in a script, you have access to all of the functions and classes defined in each package. - -If these imports are at the top of the script or **Jupyter Notebook** file, then you will be able to use those packages in any code lines that follow. - -This means that if you import a package *after* running some code that requires that package, your code will not run successfully. - - -## 2. List Package Imports Following PEP 8 Standards: Most Common First, Followed By Third Party - -PEP 8 also specifies the order in which you should list your imports as follows (starting with the most commonly used): - -> Imports should be grouped in the following order: -> Standard library imports. -> Related third party imports. -> Local application/library specific imports. -> You should put a blank line between each group of imports. - -You may be wondering, what is a standard library import? The standard library imports are commonly used tools that are general in purpose and are part of the standard library of **Python**. These including things like: - -* **os**: handle files and directories. -* **glob**: create lists of files and directories for batch processing. - -In the PEP 8 order, other commonly used packages that are general in purpose will follow such as: - -* **numpy**: work with data in array formats. -* **matplotlib**: plot data. -* * **Pandas**: to work with tabular data. - -A PEP 8 order of imports for commonly used **Python** packages for science would look something like this: - -```python -import os -import glob - -import matplotlib.pyplot as plt -import numpy as np -import pandas as pd -``` - -Note that there is a space between the standard imports (`glob` and `os`) -and the rest of the third-party imports. - -## What are Local application/library specific imports - -Local application / library specific imports refer to tool that you have created locally or just for your own work. - -TODO: more here... diff --git a/clean-modular-code/python-pep-8.md b/clean-modular-code/python-pep-8.md index f9e6504..5d070e3 100644 --- a/clean-modular-code/python-pep-8.md +++ b/clean-modular-code/python-pep-8.md @@ -262,3 +262,69 @@ Ruff is both a linter and code formatter which is why we like to use it when dev ::: +++ {"editable": true, "slideshow": {"slide_type": ""}} + +DRAFT!! + + +## Best Practices for Importing Python Packages In Scientific Code + +There are a set of best practices that you should follow when importing **Python** packages in your code. These best practices are outlined in the PEP 8 guidelines and apply to both **Python** scripts and to working in **Jupyter Notebook** files. + +## Import Python Libraries at the Top of Your Script or Notebook + +It is good practice to import all of the packages that you will need at the top of your **Python** script (.py file) or in the first code cell of a **Jupyter Notebook** file. + +This allows anyone looking at your code to immediately know what packages they need to have installed in order to successfully run the code. This rule also follows the PEP 8 conventions for **Python** code. + +```python +import os + +import pandas as pd +import numpy as np +``` + +Once you have imported all of the packages that you need to run your code in a script, you have access to all of the functions and classes defined in each package. + +If these imports are at the top of the script or **Jupyter Notebook** file, then you will be able to use those packages in any code lines that follow. + +This means that if you import a package *after* running some code that requires that package, your code will not run successfully. + + +## 2. List Package Imports Following PEP 8 Standards: Most Common First, Followed By Third Party + +PEP 8 also specifies the order in which you should list your imports as follows (starting with the most commonly used): + +> Imports should be grouped in the following order: +> Standard library imports. +> Related third party imports. +> Local application/library specific imports. +> You should put a blank line between each group of imports. + +You may be wondering, what is a standard library import? The standard library imports are commonly used tools that are general in purpose and are part of the standard library of **Python**. These including things like: + +* **os**: handle files and directories. +* **glob**: create lists of files and directories for batch processing. + +In the PEP 8 order, other commonly used packages that are general in purpose will follow such as: + +* **numpy**: work with data in array formats. +* **matplotlib**: plot data. +* * **Pandas**: to work with tabular data. + +A PEP 8 order of imports for commonly used **Python** packages for science would look something like this: + +```python +import os +import glob + +import matplotlib.pyplot as plt +import numpy as np +import pandas as pd +``` + +Note that there is a space between the standard imports (`glob` and `os`) +and the rest of the third-party imports. + +## What are Local application/library specific imports + +Local application / library specific imports refer to tool that you have created locally or just for your own work. From edfaf9aba565f28f97060b4726c3c638f77ce842 Mon Sep 17 00:00:00 2001 From: Leah Wasser Date: Mon, 7 Oct 2024 15:48:24 -0600 Subject: [PATCH 03/18] feat: fix toctree --- clean-modular-code/intro-clean-code.md | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/clean-modular-code/intro-clean-code.md b/clean-modular-code/intro-clean-code.md index b857a8e..88aaffd 100644 --- a/clean-modular-code/intro-clean-code.md +++ b/clean-modular-code/intro-clean-code.md @@ -19,7 +19,9 @@ jupyter: name: python3 --- - + +# Write Clean, Modular, DRY Code + :::{toctree} :hidden: :caption: Lessons @@ -27,7 +29,6 @@ jupyter: Intro Python Code Style -Package imports Don't Repeat Yourself Functions Function checks @@ -56,10 +57,6 @@ Clean Code: Activity 2 Clean Code: Activity 3 ::: - - - -# Write Clean, Modular, DRY Code :::{note} After completing this lesson, you will be able to: @@ -68,7 +65,7 @@ After completing this lesson, you will be able to: * Apply the PEP 8 Style Guide standards to your **Python** code. ::: -"Pythonic" code is code that follows the conventions and best practices of the Python programming language. It emphasizes code that is clear, concise, and readable--principles that adhere to Python's design philosophy. +"Pythonic" code is code that follows the conventions and best practices of the Python programming language. It emphasizes code that is clear, concise, and readable--principles that adhere to Python's design philosophy. Pythonic code also takes full advantage of Python's features which include: From df5f18337d9e24a94f7d83f164dc823c8aaa07cb Mon Sep 17 00:00:00 2001 From: Leah Wasser Date: Tue, 8 Oct 2024 14:18:09 -0600 Subject: [PATCH 04/18] feat(fix): pep 8 lesson --- clean-modular-code/python-pep-8.md | 398 +++++++++++++---------------- 1 file changed, 180 insertions(+), 218 deletions(-) diff --git a/clean-modular-code/python-pep-8.md b/clean-modular-code/python-pep-8.md index 5d070e3..6f81e62 100644 --- a/clean-modular-code/python-pep-8.md +++ b/clean-modular-code/python-pep-8.md @@ -14,206 +14,213 @@ kernelspec: +++ {"editable": true, "slideshow": {"slide_type": ""}} -# Use PEP 8 To Write Easier-to-Read Code +# Python code style for readability and usability :::{admonition} What you will learn :class: tip -* Describe the benefits of using code styles guides. -* Explain the PEP 8 style guide and how it helps promote code readability. -* Describe key components of the PEP 8 style guide, including naming conventions and white space. -* List tools to help you apply the PEP 8 style guide to your code. +* How to follow the PEP 8 style guide to write Python code that’s easy to read and understand. +* Best practices for naming variables, using comments, and formatting code. +* Tools to help you apply PEP 8 to your code automatically. ::: -## What is Python PEP 8 code style? +## Why code style and Python PEP 8 matters -Code syntax standards refer to rules associated with how code is formatted. These rules include things like: +Just like good grammar makes text easier to read, PEP 8 helps make your code easier to understand. It enforces rules on naming variables, capitalization, formatting code, and structuring your script. Well-formatted code also makes it easier for you to share code, given it will be easier for others to understand. -* How to space code elements in a script, -* How to format and create comments, and -* Naming conventions for variables, functions, and classes - -## Why use code standards when writing Python code - -Code standards help make your code more readable. Consider this page that you are reading right now. Some conventions are followed that most of us are familiar with (but may not even think about). These conventions include: - -* Capitalize the first letter of a sentence. -* Capitalize the first letter of someone's name. -* Add a space after the end of a sentence. -* Add a space after each word. - -These conventions lead to text that you can read easily, like this: - -`This is a sentence. And another sentence with a Name and a location like Florida, USA.` - -Now imagine reading a book with no spacing, no capitalization and that doesn't follow the regular English language writing conventions. This book would be difficult to read. Take the example below: - -`this is a sentence.and another sentence with a name.this -text could go on forever. whatwouldhappenifweneverusedspaces?` - -Code style standards, just like any other language standard, are designed to make code easier to read and understand. - -Below, you will learn about the PEP 8 standard for the **Python** scientific programming language. This is the standard used by many **Python** users. - -## About the PEP 8 standard for Python - -PEP 8 is the style guide that is widely used in the **Python** community. This guide includes rules about naming objects, spacing rules and even how the code is laid out. - -**Python** is developed and maintained by an open source community, and thus, it is not possible to make code standards mandatory. Rather, community members choose to adopt PEP 8 recommendations whenever possible to contribute code that can easily be read and used by the greater community of users. - -PEP 8 covers many aspects of code readability, including: - -* naming conventions -* use of comments -* line lengths -* use of white space - -## PEP 8 naming conventions - -The text in this section is summarized from the PEP 8 Style Guide published by the Python Software Foundation. - -:::{tip} +```{code-cell} ipython3 +--- +editable: true +slideshow: + slide_type: '' +--- +#some data analysis with poor formatting +import pandas as pd +from datetime import datetime +def classify_precipitation(precip_list): + avg_precip=pd.Series(precip_list).mean() + if avg_precip<100: + return'Low' + elif avg_precip>=100 and avg_precip<=150: + return'Medium' + else: + return'High' +data={'location':['Station1','Station2','Station3','Station4'],'year':[2021,2021,2021,2021],'monthly_precipitation':[[50.0,70.0,90.0,80.0],[100.0,110.0,120.0,130.0],[150.0,160.0,170.0,180.0],[200.0,210.0,220.0,230.0]],'start_date':["2021-01-01","2021-01-01","2021-01-01","2021-01-01"]} +df=pd.DataFrame(data) +df['start_date']=pd.to_datetime(df['start_date']) +df['precipitation_category']=df['monthly_precipitation'].apply(classify_precipitation) +df +``` -**Terminology Teview** ++++ {"editable": true, "slideshow": {"slide_type": ""}} -First, let's review some terminology associated with naming conventions. +Notice that by adding docstrings, spacing to the the code.... -* **Lowercase letter:** `b` +```{code-cell} ipython3 +--- +editable: true +slideshow: + slide_type: '' +--- +# Built-in libraries are imported first +from datetime import datetime +import pandas as pd -* **Uppercase letter:** `B` +# Function to classify precipitation levels +def classify_precipitation(precip_list): + """Classify average monthly precipitation into low, medium, or high. + + Parameters + ---------- + precip_list : list of float + A list of monthly precipitation values (in mm). + + Returns + ------- + str + The precipitation category: 'Low', 'Medium', or 'High'. + """ + avg_precip = pd.Series(precip_list).mean() + + # Define the precipitation ranges + if avg_precip < 100: + return 'Low' + elif 100 <= avg_precip <= 150: + return 'Medium' + else: + return 'High' + + +# Sample data for precipitation values (in mm) for different locations +data = { + 'location': ['Station1', 'Station2', 'Station3', 'Station4'], + 'year': [2021, 2021, 2021, 2021], + 'monthly_precipitation': [ + [50.0, 70.0, 90.0, 80.0], # Station1 + [100.0, 110.0, 120.0, 130.0], # Station2 + [150.0, 160.0, 170.0, 180.0], # Station3 + [200.0, 210.0, 220.0, 230.0] # Station4 + ], + 'start_date': ["2021-01-01", "2021-01-01", "2021-01-01", "2021-01-01"] +} + +df = pd.DataFrame(data) +df['start_date'] = pd.to_datetime(df['start_date']) + +# Classify precipitation levels based on ranges +df['precipitation_category'] = df['monthly_precipitation'].apply(classify_precipitation) + +df +``` -* **lowercase:** `this is all lowercase words` ++++ {"editable": true, "slideshow": {"slide_type": ""}} -* **snake case:** when words are separated by underscores: `lower_case_with_underscores` +## How to Apply PEP 8 Code Style Standards -* **Uppercase:** All words are all uppercase letters: `UPPERCASE` +It may seem overwhelming to remember all the PEP 8 rules, but tools called **code formatters** can automatically apply these standards for you. -* **Snake case** upper case: `UPPER_CASE_WITH_UNDERSCORES` +### For `.py` Files -* **CamelCase:** Every word is capitalized so they visually stand out: `CapitalizedWords`. This is sometimes also referred to as CapWords or StudlyCaps. +Use popular tools like **Black** or **Ruff**: - * Note: When using acronyms in CamelCase, capitalize all the letters of the acronym. Thus HTTPServerError is better than HttpServerError. +- **[Black](https://black.readthedocs.io/en/stable/)**: Automatically reformats code according to PEP 8. +- **[Ruff](https://docs.astral.sh/ruff/configuration/#jupyter-notebook-discovery)**: A linter and formatter that also supports import sorting with **isort**. -* **mixedCase:** (differs from CapitalizedWords by initial lowercase character!) +Both tools can be run manually or integrated into **pre-commit hooks** with Git to check your code before each commit. You can also configure them in your IDE (like VSCode, PyCharm, or Spyder) to format your code every time you save. -* **Capitalized_Words_With_Underscores:** This approach is not recommended. Use one convention and stick with it. +:::{note} +Ruff doesn’t fully support Jupyter/MyST markdown notebooks yet but can be integrated into a pre-commit workflow for GitHub repositories. ::: -### Use snake_case and all lower case for variable names - -It is recommended that you use standard naming conventions in your code. We suggest that you use **snake_case** and all lowercase letters in your code for variable and function names. Like this: -```python -variable_one -variable_two -``` - -### Use CamelCase or CapsCase for class names - -While regular variables and functions should use **snake_case**, PEP 8 -suggests that you use `CamelCase` for class definitions. - -```python -class PlotBasicObject(object): -``` +### For Jupyter Notebooks -### Avoid using single character letters that could be confused with numbers +For Jupyter Notebooks, try: +- **Notebook extensions**: Add extensions to your interface to format cells automatically. +- **nbQA**: A command-line tool that applies Black or Ruff to Jupyter Notebooks via the CLI. -Avoid using the characters: +### Running These Tools +These tools can be used in the following ways: +- **Manually**: Run on-demand to check and format your code. +- **Pre-commit hook**: Enforce code style checks before every commit. +- **IDE integration**: Automatically format code in your editor. -* 'l' (lowercase letter el), -* 'O' (uppercase letter oh), or -* 'I' (uppercase letter eye) +Using these tools ensures your code remains consistent, readable, and compliant with PEP 8, without memorizing all the rules. -as single-character variable names. +:::{admonition} Linter vs. Code Formatter +:class: note -These characters can be difficult to distinguish from numbers when -using certain font families. +- **Linter**: Checks your code and highlights issues but doesn’t automatically fix them. +- **Code Formatter**: Automatically reformats your code according to style rules. -For example, the letter `l` looks similar to the number `1`. - -## Comments and PEP 8 - -Documentation is an important part of writing great code. Below are some -of the important PEP 8 conventions associated with documentation. - -### 1. Python comments should have a space after the `#` sign with the first word capitalized +Ruff acts as both a linter and formatter, making it ideal for `.py` file workflows. +::: -Following the PEP8 style guide, single-line comments should -start with the `#` sign followed by a space. The first word of the comment should be capitalized. Like this: ++++ {"editable": true, "slideshow": {"slide_type": ""}} -`# This is a PEP 8 conforming comment` -The comment below does NOT conform to PEP 8 standards +## Why use code standards when writing Python code -`#this comment does not conform to PEP 8 standards` +Code standards make your code more readable and easier to maintain, just like writing conventions make text easier to read. Think about how we capitalize the first word of a sentence or add spaces between words—without those conventions, text would be hard to follow. Similarly, code with inconsistent formatting is difficult to understand and debug. + +For example: -### 2. Multi-line function comments (docstrings) +* Readable sentence: This is a sentence. +* Unformatted sentence: thisisasentence.withoutspacesitgetsconfusing. -Multi-line comments are most commonly used when creating docstrings. A docstring is the text that follows a function definition. This text helps you or someone using a function understand what the function does. +Using code standards like PEP 8 helps avoid such confusion, making code clearer and more professional. -Following the PEP8 style guide, you create a function docstring using three quotes `"""`. The first line of text following the quotes should be a short, concise description of what the function does. +### Some PEP 8 rules to remember -Below that, you can add as much text as you'd like that provides more detail about what the function does. +There is a style guide devoted to Python pep 8 standards that you can read [here](https://www.python.org/dev/peps/pep-0008/#naming-conventions). However, below are a handful of PEP 8 Rules that you can consider following when writing code. -example: +* Naming Conventions: Use **snake_case** for variables/functions and **CamelCase** for class names. ```python -def calculate_sum(rainfall, time="month"): - -"""Returns a single sum value of all precipitation. - -This function takes a Pandas DataFrame with time series as the index, -and calculates the total sum, aggregated by month. -""" -# Code here - -return the_total_sum +# This is a class definition +class MyClass: + """A class to process data and calculate statistics.""" + + # This is a function + def calculate_average(self, data_list): + """Calculate the average of a list of numbers.""" + total_sum = sum(data_list) + count = len(data_list) + return total_sum / count + +# Example variable names and function call +data_processor = DataProcessor() +numbers = [10, 20, 30, 40, 50] +average_value = data_processor.calculate_average(numbers) + +print(f"The average value is: {average_value}") ``` -## Line Length - -PEP 8 guidelines suggest that both code and comment lines should all be 79 characters wide (or less). This standard is common in other languages, such as **R**. +* Line Length: Limit all lines to 79 characters for better readability. :::{tip} Most text editors allow you to set up guides to see how long your code is. You can then use these guides to create line breaks in your code. ::: +* Comments: Add a space after the `#` sign and capitalize the first letter of a comment: -## Python PEP 8 rules for white space - -Some of the white space rules have already been discussed above. These including adding a single space after a comment `# Comment here`. - -There are also rules associated with spacing throughout your code. These include: +`# This is a PEP 8 conforming comment` -* **Add a blank line before a single-line comment (unless it is the first line of a cell in Jupyter Notebook)** Blank lines help to break up code visually . Consider reading this page: If all of the text was mashed together in one long paragraph, it would be more difficult to read. However, when you break the text up into related paragraphs, it becomes a lot easier to read. +* White Space: Add space between sections of code to improve clarity. +* Avoid using single-character letters that could be confused with numbers (ie the letter `l` looks similar to the number one `1` +* Add a blank line before a single-line comment (unless it is the first line of a cell in Jupyter Notebook) ```python +a = 1 -# Perform some math -a = 1+2 -b = 3+4 -c = a+b +# Here is a commment +b = 2 -# Read in and plot some -review_timeseries = pd.readcsv("pyos-data.csv") -review_timeseries.plot() ``` -The code below is more difficult to read as the spacing does not break up the text. - -```python -# Perform some math and do some things -a=1+2 -b=3+4 -c=a+b -data=pd.readcsv("pyos-data.csv") -data.plot() -``` - -* **Break up sections of code with white space:** As you are writing code, it's always good to consider readability and to break up sections of code accordingly. Breaking up your +* **Break up sections of code with white space:** Breaking up your code becomes even more important when you start working in Jupyter Notebooks which offer individual cells where you can add Markdown and code. ```python @@ -226,105 +233,60 @@ data.plot(ax=ax) plt.show() ``` -## Summary -- PEP 8 and Python +## PEP 8 naming conventions -The text above provides a broad overview of some of the PEP 8 guidelines and conventions for writing **Python** code. +:::{seealso} +The text in this section is summarized from the PEP 8 Style Guide published by the Python Software Foundation. -:::{important} -This page is not fully inclusive of all of the PEP 8 standards. ::: - -+++ - -## Tools for applying PEP 8 format to your code - -Many different tools can help you write code that is PEP 8 compliant. A tool that checks the format of your code is called a linter. - -Some linters will reformat your code so that it matches the standards. - -* [Black](https://black.readthedocs.io/en/stable/) has been a popular tool in the scientific Python ecosystem for several years. -* More recently, many people are moving to [ruff which now provides Jupyter support.](https://docs.astral.sh/ruff/configuration/#jupyter-notebook-discovery). Ruff is a perfect tool for you to use if you are developing your code in `.py` files. - - -:::{note} -Ruff doesn't currently work well with Jupyter / JupyText and myst markdown notebooks. But it can be easily configured into a .precommit workflow, which is used alongside Git and GitHub and will be applied every time you make a commit to a GitHub repo. -:::: - -The pyOpenSci community has been slowly adopting Ruff because it can run many code formatters with a single configuration file, making it a convenient and easy-to-use tool. - -:::{admonition} Linter vs. code formatter +:::{admonition} Terminology Review :class: tip -A code formatter is a tool that helps you modify your code to follow code standards. A linter checks your code and tells you if things need to be fixed, but it generally won't fix them for you. +First, let's review some terminology associated with naming conventions. + +* **Lowercase letter:** `b` +* **Uppercase letter:** `B` +* **lowercase:** `this is all lowercase words` +* **snake case:** when words are separated by underscores: `lower_case_with_underscores` +* **Uppercase:** All words are all uppercase letters: `UPPERCASE` +* **Snake case** upper case: `UPPER_CASE_WITH_UNDERSCORES` +* **CamelCase:** Every word is capitalized so they visually stand out: `CapitalizedWords`. This is sometimes also referred to as CapWords or StudlyCaps. + * Note: When using acronyms in CamelCase, capitalize all the letters of the acronym. Thus HTTPServerError is better than HttpServerError. +* **mixedCase:** (differs from CapitalizedWords by initial lowercase character!) +* **Capitalized_Words_With_Underscores:** This approach is not recommended. Use one convention and stick with it. -Ruff is both a linter and code formatter which is why we like to use it when developing both software and .py file based workflows. ::: +++ {"editable": true, "slideshow": {"slide_type": ""}} -DRAFT!! - - -## Best Practices for Importing Python Packages In Scientific Code - -There are a set of best practices that you should follow when importing **Python** packages in your code. These best practices are outlined in the PEP 8 guidelines and apply to both **Python** scripts and to working in **Jupyter Notebook** files. - -## Import Python Libraries at the Top of Your Script or Notebook - -It is good practice to import all of the packages that you will need at the top of your **Python** script (.py file) or in the first code cell of a **Jupyter Notebook** file. - -This allows anyone looking at your code to immediately know what packages they need to have installed in order to successfully run the code. This rule also follows the PEP 8 conventions for **Python** code. - -```python -import os - -import pandas as pd -import numpy as np -``` - -Once you have imported all of the packages that you need to run your code in a script, you have access to all of the functions and classes defined in each package. - -If these imports are at the top of the script or **Jupyter Notebook** file, then you will be able to use those packages in any code lines that follow. +## Best practices for importing libraries -This means that if you import a package *after* running some code that requires that package, your code will not run successfully. +### Import Python libraries at the top of your code +It’s good practice to import all required libraries at the top of your **Python** script or in the first cell of a **Jupyter Notebook**. This helps anyone understand what packages are needed to run your code. It also follows PEP 8 conventions. -## 2. List Package Imports Following PEP 8 Standards: Most Common First, Followed By Third Party +### Organize your imports into groups -PEP 8 also specifies the order in which you should list your imports as follows (starting with the most commonly used): +PEP 8 recommends organizing imports in the following order: -> Imports should be grouped in the following order: -> Standard library imports. -> Related third party imports. -> Local application/library specific imports. -> You should put a blank line between each group of imports. +1. **Standard Library Imports**: These are built-in modules that come with Python, such as `os` and `glob`. You can find the full list [here](https://docs.python.org/3/library/index.html). +2. **Third-Party Imports**: Libraries that you install via `pip`, like `numpy` and `pandas`. +3. **Local Imports**: Code or modules specific to your project. -You may be wondering, what is a standard library import? The standard library imports are commonly used tools that are general in purpose and are part of the standard library of **Python**. These including things like: - -* **os**: handle files and directories. -* **glob**: create lists of files and directories for batch processing. - -In the PEP 8 order, other commonly used packages that are general in purpose will follow such as: - -* **numpy**: work with data in array formats. -* **matplotlib**: plot data. -* * **Pandas**: to work with tabular data. - -A PEP 8 order of imports for commonly used **Python** packages for science would look something like this: +Here’s an example following PEP 8 conventions: ```python import os import glob -import matplotlib.pyplot as plt import numpy as np import pandas as pd -``` +import matplotlib.pyplot as plt -Note that there is a space between the standard imports (`glob` and `os`) -and the rest of the third-party imports. +from my_module import my_function +``` -## What are Local application/library specific imports +### Why organize imports? -Local application / library specific imports refer to tool that you have created locally or just for your own work. +Organizing your imports this way ensures your code is readable and follows widely accepted practices. Importing libraries at the top also makes it easier to debug and see which dependencies are required to run the code. From 35c53ac3f209f3a46ac5206783e1d212c5f67e4a Mon Sep 17 00:00:00 2001 From: Leah Wasser Date: Tue, 8 Oct 2024 14:23:33 -0600 Subject: [PATCH 05/18] feat(fix): pep 8 lesson --- clean-modular-code/python-pep-8.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/clean-modular-code/python-pep-8.md b/clean-modular-code/python-pep-8.md index 6f81e62..aa469f4 100644 --- a/clean-modular-code/python-pep-8.md +++ b/clean-modular-code/python-pep-8.md @@ -236,7 +236,7 @@ plt.show() ## PEP 8 naming conventions :::{seealso} -The text in this section is summarized from the PEP 8 Style Guide published by the Python Software Foundation. +For the entire pep-8 style guide see: PEP 8 Style Guide published by the Python Software Foundation. ::: @@ -270,7 +270,7 @@ It’s good practice to import all required libraries at the top of your **Pytho PEP 8 recommends organizing imports in the following order: -1. **Standard Library Imports**: These are built-in modules that come with Python, such as `os` and `glob`. You can find the full list [here](https://docs.python.org/3/library/index.html). +1. **Standard Library Imports**: These built-in modules come with Python, such as `os` and `glob`. You can find the full list [here](https://docs.python.org/3/library/index.html). 2. **Third-Party Imports**: Libraries that you install via `pip`, like `numpy` and `pandas`. 3. **Local Imports**: Code or modules specific to your project. From 8813e39cc4523d6922a6a0b5ae4a840310d5a6ea Mon Sep 17 00:00:00 2001 From: Leah Wasser Date: Thu, 17 Oct 2024 15:59:48 -0600 Subject: [PATCH 06/18] Apply suggestions from code review Co-authored-by: Carol Willing --- clean-modular-code/intro-clean-code.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clean-modular-code/intro-clean-code.md b/clean-modular-code/intro-clean-code.md index 88aaffd..0b3b114 100644 --- a/clean-modular-code/intro-clean-code.md +++ b/clean-modular-code/intro-clean-code.md @@ -65,7 +65,7 @@ After completing this lesson, you will be able to: * Apply the PEP 8 Style Guide standards to your **Python** code. ::: -"Pythonic" code is code that follows the conventions and best practices of the Python programming language. It emphasizes code that is clear, concise, and readable--principles that adhere to Python's design philosophy. +"Pythonic" code follows the conventions and best practices of the Python programming language. It emphasizes clear, concise, and readable code—the principles of Python's design philosophy. Pythonic code also takes full advantage of Python's features which include: From a3323b6371f9bb5c9904d5ff4539821b4f237ea1 Mon Sep 17 00:00:00 2001 From: Leah Wasser Date: Thu, 17 Oct 2024 16:00:04 -0600 Subject: [PATCH 07/18] Apply suggestions from code review Co-authored-by: Jonny Saunders --- clean-modular-code/python-pep-8.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clean-modular-code/python-pep-8.md b/clean-modular-code/python-pep-8.md index aa469f4..b0cecdd 100644 --- a/clean-modular-code/python-pep-8.md +++ b/clean-modular-code/python-pep-8.md @@ -27,7 +27,7 @@ kernelspec: ## Why code style and Python PEP 8 matters -Just like good grammar makes text easier to read, PEP 8 helps make your code easier to understand. It enforces rules on naming variables, capitalization, formatting code, and structuring your script. Well-formatted code also makes it easier for you to share code, given it will be easier for others to understand. +Just like good grammar makes text easier to read, [PEP 8](https://peps.python.org/pep-0008/) helps make your code easier to understand. It enforces rules on naming variables, capitalization, formatting code, and structuring your script. Well-formatted code also makes it easier for you to share code, given it will be easier for others to understand. ```{code-cell} ipython3 --- From b49f3febe66ab76b5e66a832a14f1e31f06783c0 Mon Sep 17 00:00:00 2001 From: Leah Wasser Date: Thu, 17 Oct 2024 16:00:25 -0600 Subject: [PATCH 08/18] Apply suggestions from code review Co-authored-by: Jonny Saunders --- clean-modular-code/python-pep-8.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/clean-modular-code/python-pep-8.md b/clean-modular-code/python-pep-8.md index b0cecdd..e8b0472 100644 --- a/clean-modular-code/python-pep-8.md +++ b/clean-modular-code/python-pep-8.md @@ -39,7 +39,10 @@ slideshow: import pandas as pd from datetime import datetime def classify_precipitation(precip_list): - avg_precip=pd.Series(precip_list).mean() + avg_precip=pd.Series( +precip_list + ).mean( + ) if avg_precip<100: return'Low' elif avg_precip>=100 and avg_precip<=150: From f98f6db5f25da0e768b6de740e55c3018450df8c Mon Sep 17 00:00:00 2001 From: Leah Wasser Date: Thu, 17 Oct 2024 16:00:44 -0600 Subject: [PATCH 09/18] Apply suggestions from code review Co-authored-by: Jonny Saunders --- clean-modular-code/python-pep-8.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/clean-modular-code/python-pep-8.md b/clean-modular-code/python-pep-8.md index e8b0472..9bc4daf 100644 --- a/clean-modular-code/python-pep-8.md +++ b/clean-modular-code/python-pep-8.md @@ -45,10 +45,11 @@ precip_list ) if avg_precip<100: return'Low' - elif avg_precip>=100 and avg_precip<=150: - return'Medium' - else: - return'High' + elif avg_precip>=100 and avg_precip<=150: return'Medium'; + + + + return'High' data={'location':['Station1','Station2','Station3','Station4'],'year':[2021,2021,2021,2021],'monthly_precipitation':[[50.0,70.0,90.0,80.0],[100.0,110.0,120.0,130.0],[150.0,160.0,170.0,180.0],[200.0,210.0,220.0,230.0]],'start_date':["2021-01-01","2021-01-01","2021-01-01","2021-01-01"]} df=pd.DataFrame(data) df['start_date']=pd.to_datetime(df['start_date']) From 7bf66887c62f0a831d74d5ff964c2e5bf1e7e9a4 Mon Sep 17 00:00:00 2001 From: Leah Wasser Date: Thu, 17 Oct 2024 16:57:23 -0600 Subject: [PATCH 10/18] Update clean-modular-code/python-pep-8.md Co-authored-by: Jonny Saunders --- clean-modular-code/python-pep-8.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clean-modular-code/python-pep-8.md b/clean-modular-code/python-pep-8.md index 9bc4daf..6f379d0 100644 --- a/clean-modular-code/python-pep-8.md +++ b/clean-modular-code/python-pep-8.md @@ -52,7 +52,7 @@ precip_list return'High' data={'location':['Station1','Station2','Station3','Station4'],'year':[2021,2021,2021,2021],'monthly_precipitation':[[50.0,70.0,90.0,80.0],[100.0,110.0,120.0,130.0],[150.0,160.0,170.0,180.0],[200.0,210.0,220.0,230.0]],'start_date':["2021-01-01","2021-01-01","2021-01-01","2021-01-01"]} df=pd.DataFrame(data) -df['start_date']=pd.to_datetime(df['start_date']) +df["start_date"]=pd.to_datetime(df[str('start_date')]) df['precipitation_category']=df['monthly_precipitation'].apply(classify_precipitation) df ``` From 75d4d9b02c28a7b5d56e74225ad3df8c00ed0547 Mon Sep 17 00:00:00 2001 From: Leah Wasser Date: Thu, 17 Oct 2024 16:57:38 -0600 Subject: [PATCH 11/18] Update clean-modular-code/python-pep-8.md Co-authored-by: Carol Willing --- clean-modular-code/python-pep-8.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clean-modular-code/python-pep-8.md b/clean-modular-code/python-pep-8.md index 6f379d0..4ab62fa 100644 --- a/clean-modular-code/python-pep-8.md +++ b/clean-modular-code/python-pep-8.md @@ -122,7 +122,7 @@ df ## How to Apply PEP 8 Code Style Standards -It may seem overwhelming to remember all the PEP 8 rules, but tools called **code formatters** can automatically apply these standards for you. +It may seem overwhelming to remember all the PEP 8 rules, but tools called **code linters and formatters** can identify and automatically apply these standards for you. ### For `.py` Files From bcb5b65a8345fc1bc79d7737e20dca44accfedee Mon Sep 17 00:00:00 2001 From: Leah Wasser Date: Thu, 17 Oct 2024 17:02:30 -0600 Subject: [PATCH 12/18] Update clean-modular-code/python-pep-8.md Co-authored-by: Carol Willing --- clean-modular-code/python-pep-8.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clean-modular-code/python-pep-8.md b/clean-modular-code/python-pep-8.md index 4ab62fa..67f6ac8 100644 --- a/clean-modular-code/python-pep-8.md +++ b/clean-modular-code/python-pep-8.md @@ -178,7 +178,7 @@ Using code standards like PEP 8 helps avoid such confusion, making code clearer ### Some PEP 8 rules to remember -There is a style guide devoted to Python pep 8 standards that you can read [here](https://www.python.org/dev/peps/pep-0008/#naming-conventions). However, below are a handful of PEP 8 Rules that you can consider following when writing code. +There is a style guide devoted to Python PEP 8 standards that you can read [here](https://www.python.org/dev/peps/pep-0008/#naming-conventions). However, below are a handful of PEP 8 Rules that you can consider following when writing code. * Naming Conventions: Use **snake_case** for variables/functions and **CamelCase** for class names. From 270946b53fe9c462a8316bd0bf662d7926bc624e Mon Sep 17 00:00:00 2001 From: Leah Wasser Date: Thu, 17 Oct 2024 17:03:49 -0600 Subject: [PATCH 13/18] Update clean-modular-code/python-pep-8.md Co-authored-by: Carol Willing --- clean-modular-code/python-pep-8.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/clean-modular-code/python-pep-8.md b/clean-modular-code/python-pep-8.md index 67f6ac8..ef2fc3c 100644 --- a/clean-modular-code/python-pep-8.md +++ b/clean-modular-code/python-pep-8.md @@ -194,9 +194,10 @@ class MyClass: count = len(data_list) return total_sum / count -# Example variable names and function call +# Call to create an object of a class data_processor = DataProcessor() numbers = [10, 20, 30, 40, 50] +# Examples of variable names and method call average_value = data_processor.calculate_average(numbers) print(f"The average value is: {average_value}") From 7decb19df2d6a1ce922f23cd30b01ae55dec7573 Mon Sep 17 00:00:00 2001 From: Leah Wasser Date: Thu, 17 Oct 2024 17:04:25 -0600 Subject: [PATCH 14/18] Apply suggestions from code review Co-authored-by: Jonny Saunders Co-authored-by: Carol Willing --- clean-modular-code/python-pep-8.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/clean-modular-code/python-pep-8.md b/clean-modular-code/python-pep-8.md index ef2fc3c..d0d7d86 100644 --- a/clean-modular-code/python-pep-8.md +++ b/clean-modular-code/python-pep-8.md @@ -187,7 +187,7 @@ There is a style guide devoted to Python PEP 8 standards that you can read [here class MyClass: """A class to process data and calculate statistics.""" - # This is a function + # This is a method def calculate_average(self, data_list): """Calculate the average of a list of numbers.""" total_sum = sum(data_list) @@ -199,7 +199,7 @@ data_processor = DataProcessor() numbers = [10, 20, 30, 40, 50] # Examples of variable names and method call average_value = data_processor.calculate_average(numbers) - +## Example of function call print(f"The average value is: {average_value}") ``` From 23ccc2e1fe125b34d140fdc853a11bcef6ea65b9 Mon Sep 17 00:00:00 2001 From: Leah Wasser Date: Thu, 17 Oct 2024 17:04:42 -0600 Subject: [PATCH 15/18] Update clean-modular-code/python-pep-8.md Co-authored-by: Carol Willing --- clean-modular-code/python-pep-8.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clean-modular-code/python-pep-8.md b/clean-modular-code/python-pep-8.md index d0d7d86..c9e32a1 100644 --- a/clean-modular-code/python-pep-8.md +++ b/clean-modular-code/python-pep-8.md @@ -213,7 +213,7 @@ Most text editors allow you to set up guides to see how long your code is. You c `# This is a PEP 8 conforming comment` -* White Space: Add space between sections of code to improve clarity. +* White Space: Add space between sections of code to improve readability. * Avoid using single-character letters that could be confused with numbers (ie the letter `l` looks similar to the number one `1` * Add a blank line before a single-line comment (unless it is the first line of a cell in Jupyter Notebook) From 21f7b4916d20faed71d04562219f49f0d0440c45 Mon Sep 17 00:00:00 2001 From: Leah Wasser Date: Thu, 17 Oct 2024 17:04:56 -0600 Subject: [PATCH 16/18] Update clean-modular-code/python-pep-8.md Co-authored-by: Carol Willing --- clean-modular-code/python-pep-8.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clean-modular-code/python-pep-8.md b/clean-modular-code/python-pep-8.md index c9e32a1..4efd369 100644 --- a/clean-modular-code/python-pep-8.md +++ b/clean-modular-code/python-pep-8.md @@ -215,7 +215,7 @@ Most text editors allow you to set up guides to see how long your code is. You c * White Space: Add space between sections of code to improve readability. * Avoid using single-character letters that could be confused with numbers (ie the letter `l` looks similar to the number one `1` -* Add a blank line before a single-line comment (unless it is the first line of a cell in Jupyter Notebook) +* Add a blank line before a single-line comment (unless it is the first line of a cell in Jupyter Notebook or part of a code block) ```python a = 1 From e005a26632e16bfe149c4837f99db82160288c06 Mon Sep 17 00:00:00 2001 From: Leah Wasser Date: Thu, 17 Oct 2024 17:05:19 -0600 Subject: [PATCH 17/18] Update clean-modular-code/python-pep-8.md Co-authored-by: Carol Willing --- clean-modular-code/python-pep-8.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clean-modular-code/python-pep-8.md b/clean-modular-code/python-pep-8.md index 4efd369..4423503 100644 --- a/clean-modular-code/python-pep-8.md +++ b/clean-modular-code/python-pep-8.md @@ -241,7 +241,7 @@ plt.show() ## PEP 8 naming conventions :::{seealso} -For the entire pep-8 style guide see: PEP 8 Style Guide published by the Python Software Foundation. +For the entire pep-8 style guide see: Python's PEP 8 Style Guide. ::: From 77c96b2e49ae6582550e6eccc4ac6711408f85f7 Mon Sep 17 00:00:00 2001 From: Leah Wasser Date: Thu, 17 Oct 2024 17:06:29 -0600 Subject: [PATCH 18/18] Update clean-modular-code/python-pep-8.md Co-authored-by: Carol Willing --- clean-modular-code/python-pep-8.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clean-modular-code/python-pep-8.md b/clean-modular-code/python-pep-8.md index 4423503..ccd2d22 100644 --- a/clean-modular-code/python-pep-8.md +++ b/clean-modular-code/python-pep-8.md @@ -294,4 +294,4 @@ from my_module import my_function ### Why organize imports? -Organizing your imports this way ensures your code is readable and follows widely accepted practices. Importing libraries at the top also makes it easier to debug and see which dependencies are required to run the code. +Organizing your imports this way ensures your code is readable and follows widely accepted practices. Importing libraries at the top also makes it easier to scan for a specific library, debug dependencies, and see which dependencies are required to run the code.