No history yet

Architectural Logic

From Code to Architecture

You already know how to write Python. You can loop through data, use conditional logic, and store information in variables. Now, it's time to stop thinking in lines of code and start thinking like an architect. Building a useful application isn't just about syntax; it's about structure, planning, and seeing the bigger picture.

The first step is problem decomposition. Instead of trying to solve one giant problem, you break it down into smaller, self-contained tasks. Each task becomes a function. This approach forces clarity. If you can't describe a task simply, you probably don't understand it well enough yet. This mindset is central to the principle: Don't Repeat Yourself. When you find yourself writing the same block of code more than once, it's a signal to create a reusable function.

Plan Before You Code

Before you write a single function, sketch out the entire script's flow. A powerful tool for this is . It's a way of writing out your program's logic in plain English, without worrying about exact Python syntax. This helps you focus purely on the steps required to solve the problem. What data do you need? Where does it come from? What transformations happen? Where does the result go? Answering these questions first saves you from writing code that doesn't fit into the larger structure.

For example, pseudocode for a simple file cleanup script might look like this:

  1. Get the target directory.
  2. For each file in the directory:
  3. If the file is older than 30 days:
  4. Move the file to an 'archive' folder.

This simple outline clarifies the logic before any code is written. Once the plan is solid, you can start building the project's file structure. A well-organised project is easier to navigate and maintain.

project_folder/
├── data/
│   └── source_files/
├── reports/
├── archive/
└── main_script.py

Working with Files

Almost every automation script interacts with the file system. In the past, this often involved messy string manipulation to build file paths. Modern Python offers a much better solution: the library. It treats paths as objects with useful methods, not just as simple strings. This object-oriented approach makes your code cleaner, more readable, and less prone to errors, especially across different operating systems like Windows, macOS, and Linux.

Instead of manually joining strings with slashes, you can use the / operator directly on Path objects. This makes creating paths intuitive and ensures the correct separator is always used.

from pathlib import Path

# Define the base directory of your project
base_path = Path.cwd() # cwd() gets the current working directory

# Create a path to a specific file
data_folder = base_path / 'data' / 'source_files'
report_file = data_folder / 'october_sales.csv'

print(f"The full path is: {report_file}")

# Check if a file exists before trying to open it
if report_file.exists():
    print("File found!")
else:
    print("File not found.")

What happens if something goes wrong, like a file not being found or not having the right permissions? Unhandled errors will crash your script. To build robust applications, you need to anticipate and manage these potential failures gracefully. This is where try...except blocks come in. You place the code that might fail inside the try block, and the code to handle the error goes in the except block.

from pathlib import Path

file_path = Path('non_existent_file.txt')

try:
    # This line will cause a FileNotFoundError
    with open(file_path, 'r') as f:
        content = f.read()
    print("File read successfully!")
except FileNotFoundError:
    print(f"Error: The file at {file_path} was not found.")
except PermissionError:
    print(f"Error: Do not have permission to read {file_path}.")

print("The script continues to run after handling the error.")

By catching specific exceptions like FileNotFoundError, you can provide clear, helpful feedback to the user and allow the program to continue running or shut down cleanly, rather than crashing unexpectedly.

Time to check your understanding of these architectural concepts.

Quiz Questions 1/5

What is the primary motivation behind the DRY (Don't Repeat Yourself) principle in programming?

Quiz Questions 2/5

Which of the following describes the main advantage of using the pathlib library over simple string manipulation for handling file paths in Python?

With these principles of structure and error handling, you're ready to start building more complex and reliable automation scripts.