Create deterministic unique labels with suffixes
Also published in our Blogger archive.
When a list can already contain suffix-shaped labels, counting only each base name is insufficient: a generated api-2 may collide with an input api-2. This example instead keeps a used set of every emitted label. For each input in encounter order, it first tries the unchanged base. If that candidate is unavailable, the loop tries base-2, then base-3, until it finds an unused string.
For the concrete input ['api-2', 'api', 'api', 'worker', 'worker'], the first api remains api, while the second cannot use api-2 because that label was supplied earlier. It therefore becomes api-3. The output is deterministic because the input order and suffix search order are explicit; it does not depend on iterating a set. The assertions check both the expected ordered result and that all labels in this fixture are distinct.
Python's set.add records each emitted candidate, and membership testing uses in. The f-string used to form suffixes requires Python 3.6 or later; this whole example otherwise uses long-established standard-language features. It is not a reservation service: simultaneous processes can still choose the same label unless a shared store enforces uniqueness. Very large runs with many occupied suffixes for one base may also require many loop iterations.
AI assistance disclosure: this article was drafted with AI assistance and checked against the cited Python documentation.
labels = ["api-2", "api", "api", "worker", "worker"]
used = set()
unique = []
for base in labels:
candidate = base
suffix = 2
while candidate in used:
candidate = f"{base}-{suffix}"
suffix += 1
used.add(candidate)
unique.append(candidate)
assert unique == ["api-2", "api", "api-3", "worker", "worker-2"]
assert len(unique) == len(set(unique))
print(unique)
['api-2', 'api', 'api-3', 'worker', 'worker-2']