The previous examples have applied our process to small blocks of code. In the next example, we’ll apply it to a larger function. As you’ll see, this method can help you break down your code by helping you identify what pieces you can break away.
Imagine we have a system that records stock purchases. Each transaction has four pieces of data:
time (a precise date and time
of the purchase)
price (e.g., $600)
For some strange reason, the data is spread across three separate
database tables, as illustrated here. In each database, the
time is the unique primary key.
Now we need to write a
program to join the three tables back together (as an SQL
JOIN operation would do). This step should be
easy because the rows are all sorted by
time, but unfortunately some of the rows are
missing. You want to find all the rows where all three
times match up, and ignore any rows that can’t
be lined up, as shown in the previous illustration.
Here is some Python code that finds all the matching rows:
def PrintStockTransactions(): stock_iter = db_read("SELECT time, ticker_symbol FROM ...") price_iter = ... num_shares_iter = ... # Iterate through all the rows of the 3 tables in parallel. while stock_iter and price_iter and num_shares_iter: stock_time = stock_iter.time price_time = price_iter.time num_shares_time = num_shares_iter ...