python, generate simple unique id
In Python, you can generate simple unique IDs using several methods, depending on your requirements. Here are a few ways to generate different types of unique IDs:
uuid
module:import uuid
unique_id = uuid.uuid4() # Generates a random UUID
print(unique_id)
secrets
module for a secure random string (useful for tokens):import secrets
unique_id = secrets.token_hex(8) # Generates a secure random hex string
print(unique_id)
class SimpleUniqueIdGenerator:
def __init__(self, prefix=''):
self.counter = 0
self.prefix = prefix
def generate_id(self):
self.counter += 1
return f"{self.prefix}{self.counter}"
id_generator = SimpleUniqueIdGenerator('ID-')
unique_id = id_generator.generate_id()
print(unique_id)
hashlib
library to create a hash of some unique data:import hashlib
import time
def generate_unique_id(data):
unique_data = f"{data}{time.time()}"
return hashlib.sha256(unique_data.encode()).hexdigest()
unique_id = generate_unique_id('my_unique_data')
print(unique_id)
time
module to generate a unique ID based on the current time (not recommended for high security, as it can be predictable):import time
unique_id = str(int(time.time() * 1000000)) # Microsecond precision
print(unique_id)
Choose the method that best fits your use case. For most applications, using uuid.uuid4()
is sufficient to ensure global uniqueness. If you're generating tokens or need cryptographic security, consider using secrets.token_hex()
. If you need something simple and your application doesn't require globally unique IDs, a simple counter might be enough.