Member-only story

Generating Unique Transaction IDs in Python: Two Approaches

Neural pAi
2 min readMar 26, 2023

--

Introduction:

When working with financial applications or any system that deals with transactions, generating unique transaction IDs is crucial. In this article, we will explore two different approaches to create unique transaction IDs in Python, using custom generator functions and the built-in itertools module.

Approach 1: Custom Generator Function

In this approach, we define a transaction_id generator function that takes a start_id as input and increments it by 1 in each iteration using a generator. The generator yields the incremented value.

def transaction_id(start_id):
while True:
start_id += 1
yield start_id

class Account:
transaction_id = transaction_id(100)

def make_transaction(self):
return next(Account.transaction_id)

a1 = Account()
a2 = Account()

print(a1.make_transaction())
print(a2.make_transaction())
print(a1.make_transaction())

Approach 2: Using itertools.count

In this approach, we use the itertools.count function from the itertools module. This function creates an iterator that generates an arithmetic sequence with the specified starting value and step.

import itertools

class Account…

--

--

No responses yet