Trending

World technology news

→
Reading two depots’ barcode scans in one ordered Python stream
Software Engineering · 2026
Software Engineering

Reading two depots’ barcode scans in one ordered Python stream

Five barcode scans show how to break timestamp ties, handle an empty depot and detect a late ordering error before handing over a dispatch report.

Developer's JournalPublished: Dec 3, 20266 min read
Reading progress0%
In this article
  1. When two depots scan at the same minute
  2. Giving a tie an order the business can explain
  3. The contract behind a small generator
  4. Following five rows through the merge
  5. An ordering error can arrive after output has started
  6. The memory bill and the wait for a first row
  7. Three checks before handing over the report

When two depots scan at the same minute

Two depots send their morning barcode scans to a dispatch team. Both files are already in time order. Appending one file to the other puts the early scans from the second depot halfway through the dispatch report. Sorting everything together would fix the report, at the cost of collecting the entire delivery before the reader gets the first row. Each source already offers a useful promise. Its next scan cannot precede the scan just read from it. Python’s heapq.merge uses that promise to give a reader a single ordered stream. A five-scan example makes the ordering decision visible, including what happens when two depots record the same minute.

Giving a tie an order the business can explain

Minute alone leaves two decisions unresolved. Both depots scan at nine, and depot A scans twice at two minutes past nine. The report uses the depot code for equal times and the original line number for equal times at the same depot. Supplying the files to the program in another order now produces the same report. This depends on the depot code identifying a single stream. Two independent scanners at one depot would need an additional device identifier or a shared sequence number. The parcel reference travels with the row. It does not have to be unique. Scanning a parcel twice can be important evidence in a dispatch inquiry.

Application flowConceptual sketch · summary of the article's technical flow

The contract behind a small generator

In the example, every time is a fixed-width UTC hour and minute on the same date. Lexical ordering works under that specific contract. Files crossing midnight need a date, and timestamps with different offsets need a common time basis. A production parser should validate the input format before comparing times and retain enough information to identify a bad row. The generator below enforces one narrower property. It remembers the preceding minute and rejects a decrease. Equal minutes are permitted because the third row in A genuinely occurred in the same minute as the second. The stable line number makes those two rows distinguishable.

Following five rows through the merge

Run the example as a standalone Python file. The two lists stand in for file readers that yield the same pair of values. At the first comparison both heads say nine o’clock, so A supplies K17. The next A record is two minutes later. B can now supply K31 and then K32 before A is selected again. The final two records have the same time and depot. Their local line numbers settle the order. The output shown here was collected by running the program. Tracing which input advances at each step also helps explain a surprising result when a third source is introduced.

from heapq import merge

def scans(site, rows):
    previous = None
    for line, (utc, parcel) in enumerate(rows, start=1):
        if previous is not None and utc < previous:
            raise ValueError(f"{site} line {line} out of order")
        previous = utc
        yield utc, site, line, parcel

a = [("09:00", "K17"), ("09:02", "K19"), ("09:02", "K20")]
b = [("09:00", "K31"), ("09:01", "K32")]
for utc, site, line, parcel in merge(scans("A", a), scans("B", b)):
    print(utc, site, line, parcel)

# Observed output
# 09:00 A 1 K17
# 09:00 B 1 K31
# 09:01 B 2 K32
# 09:02 A 2 K19
# 09:02 A 3 K20

An ordering error can arrive after output has started

Suppose B reports an 08:59 scan after its 09:01 scan. The reader cannot detect that decrease until it reaches the bad line. Several earlier records may already have gone downstream. For a complete dispatch file, write into a temporary destination and publish the result after exhausting both iterators successfully. For a live view, expose whether the report has finished and retain the failing source and line number. A consumer that inspects one good row has learned nothing about the unread suffix. Testing with a bad line at the end forces the test to exercise this distinction and the delivery system to decide what its completion signal means.

The memory bill and the wait for a first row

The merge keeps the heads of active inputs rather than collecting all scan records. Memory therefore depends on the number of open streams, plus buffers used by readers and the destination. Longer files from two depots present a different problem from opening thousands of small files at once. File descriptor limits may matter in the second case. Latency also deserves attention. Before seeing the head of a source, the consumer cannot know whether that source holds the earliest record. A closed empty file answers the question quickly. A network device that stays silent for hours needs an explicit promise about how late its records may arrive.

Three checks before handing over the report

Reversing the order in which the sources are passed produces the same five rows. Adding an empty depot leaves the result intact. An earlier time appended to B triggers an error identifying line three when the merged iterator is consumed to completion. Together these tests cover reproducibility, empty inputs and a late violation. On a real shift, retain the input file identifiers and counts with the completed report so the supervisor can identify which file to send again. A later change from UTC to local time belongs in the reader’s validation. That is where the assumptions that make the report reproducible are first applied.

Be the first reader ✎ Write a comment

Reader discussion

Discussion prompt

Which bottleneck would you expect as this solution scales?

No comments yet. Be the first to contribute.

Write a comment

Comments are real visitor contributions. Repeated, link-heavy or abusive submissions may be limited.