Preserve Inventory Deficits with Counter.subtract
Subtracting an order from stock can produce both remaining stock and shortages. Counter subtraction operators discard nonpositive results, which can hide shortages in an audit. Use subtract() on a copy when the signed balance matters.
Tested with Python 3.12.14 on Linux. The example uses only the standard library.
Prepare an isolated directory
Run this setup in Bash. If either command fails, stop before saving any files.
practice_dir=$(mktemp -d) && cd "$practice_dir"Keep the balance and the remainder separately
This example uses nonnegative integer stock and request counts. Sorting each report makes the output independent of insertion order. All operations stay in memory.
Save as count_deficits.py:
from collections import Counter
available = Counter(apples=5, pears=2, plums=1)
requested = Counter(apples=3, pears=4, plums=1, kiwis=2)
remaining = available - requested
balance = available.copy()
balance.subtract(requested)
print("Positive remainder:", dict(sorted(remaining.items())))
print("Signed balance:", dict(sorted(balance.items())))
print("Shortages:", dict(sorted((-balance).items())))
print("Available unchanged:", dict(sorted(available.items())))
pruned = balance.copy()
pruned -= Counter()
print("After -= empty:", dict(sorted(pruned.items())))
assert balance["pears"] == -2
assert balance["plums"] == 0 and "plums" in balance
assert "pears" not in remainingRun:
python3 count_deficits.pyOutput:
Positive remainder: {'apples': 2}
Signed balance: {'apples': 2, 'kiwis': -2, 'pears': -2, 'plums': 0}
Shortages: {'kiwis': 2, 'pears': 2}
Available unchanged: {'apples': 5, 'pears': 2, 'plums': 1}
After -= empty: {'apples': 2}Avoid pruning an audit balance
The positive remainder contains only apples. The signed balance also keeps pears and kiwis at minus two and plums at zero. A missing key reads as zero in a Counter, so key membership is needed when an explicit zero has meaning.
Unary minus creates a new counter containing the magnitudes of negative counts, which gives the shortage report here. It does not change the balance.
Even subtracting an empty counter with -= removes nonpositive counts. Avoid multiset arithmetic on a balance you intend to preserve. Keep separate objects for the full audit and a positive-only view, and validate incoming quantities before changing real inventory. This example does not implement concurrent stock reservations or persistence.
Clean up
From the practice directory, remove only the example file. Return to the previous directory before removing the now-empty temporary directory.
rm -- count_deficits.py
cd - >/dev/null
rmdir -- "$practice_dir"Reference
Acknowledgements
This post was created with assistance from AI.