Write Clean, Modular, DRY Code#

Note

After completing this lesson, you will be able to:

  • List 2-4 characteristics of writing clean code.

  • Apply the PEP 8 Style Guide standards to your Python code.

“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:

  • list comprehensions,

  • generators, and

  • context managers,

to write more elegant and efficient code.

Characteristics of Pythonic code#

It’s Readable#

Pythonic code is easy to read and understand, often adhering to the Zen of Python (a set of guiding principles for Python’s design).

Readable code uses descriptive (expressive) variable names and adheres to PEP 8 style guidelines.

# The Zen of Python 
import this
# Not Pythonic
import datetime
foovar = datetime.date.today().strftime("%y-%m-%d")
foovar
# Pythonic
import datetime
todays_date = datetime.date.today().strftime("%y-%m-%d")
todays_date

Compare the variable foovar to todays_date. Which variable name tells you more about the information that it contains?

It’s Concise#

Pythonic code is concise but not at the expense of clarity. An example of concise code is to use features like list comprehensions and built-in functions.

# Non-Pythonic
result = []
for i in range(10):
   result.append(i * 2)
result
# Pythonic
result = [i * 2 for i in range(10)]
result
# More Pythonic
languages = ["python", "julia", "rust"]
i=0
for language in(languages):
    i+=1
    print(f"{i}: {language}")
# More Pythonic
a = ["python", "julia", "rust"]
for i, language in enumerate(languages):
    print(f"{i}: {language}")

Clean code is DRY & avoids repitition#

Pythonic code avoids repetition. DRY (Don’t Repeat Yourself) code is written in a way that both avoids repetition and is well organized. This makes it easier to maintain and extend.

Pythonic code is expressive#

Pythonic code communicates the programmer’s intent clearly, making it easier for others to understand the purpose of the code at a glance.

Note that the function below has an easy-to-understand name and clear docstring. Some people will even suggest adding a verb that explains what the function does, such as:

convert_fahr_kelvin()

def fahr_to_kelvin(fahr):
    return ((fahr - 32) * (5 / 9)) + 273.15

Pythonic code is well-documented#

Docstrings are Pythonic because they prioritize code readability and clarity, providing clear descriptions of a function’s purpose, parameters, and return values. By embedding documentation directly in the code, docstrings make it easy for developers to understand and use functions or classes without needing to read the implementation details.

Documentation can mean many different things. When you are writing code, a combination of expressive names combined with sparsely added comments can go a long way towards making your code easier to read.

Pythonic code reflects Python’s emphasis on readability and simplicity. A well-known phrase from the Zen of Python is: “There should be one—and preferably only one—obvious way to do it,” which is a core idea behind writing Pythonic code.

def fahr_to_kelvin(fahr):
    """
    Convert temperature from Fahrenheit to Kelvin.

    Parameters
    ----------
    fahr : float
        Temperature in Fahrenheit.

    Returns
    -------
    float
        Temperature in Kelvin.
    """
    return ((fahr - 32) * (5 / 9)) + 273.15

Tools to help you write better, more Pythonic code - code formatters, linters and LLM’s#

While the above tasks used to require manual code editing, in today’s world, you can use a suite of automated tools such as linters and code formatters, combined with LLM’s to help you write better, cleaner and more Pythonic code for scientific workflows.

LLMS#

LLMs (Large Language Models) can be useful for…

however, it’s important that you are careful about how you use them because

  • ethical issues

  • they are often wrong

  • they make up stuff

  • etc. however with correct prompts, and if you build your eye for identifying problems, and combined with tools that will help you with your code, as you write it, they can be effective tools in your workflow dev process.

In the next lessons, you will learn more about making tools and approaches to making your code more Pythonic

You will then learn about tools that you can use to format your code and identify problem points including:

  • LLM’s like GitHub co-pilot

  • ChatGPT

  • Google Gemini

Code formatters like:

  • black

  • ruff