2009-07-31 19 views
97

Devo generare un ID univoco basato su un valore casuale.Come posso generare un ID univoco in Python?

+3

Puoi essere più specifico su che tipo di ID univoco. Ha bisogno di essere un numero? o può contenere lettere? Fornisci alcuni esempi del tipo di id. – MitMaro

+0

Possibilmente rilevanti, tutti gli oggetti hanno un id 'id (my_object)', o 'id (self)'.Questo è stato sufficiente per me considerando che tutto ciò che è in Python è un oggetto e ha un id numerico; stringhe: 'id ('Hello World')' classi: 'id ('Hello World')', tutto ha un id. – ThorSummoner

+1

In realtà stavo avendo problemi con l'uso di id, sembrava avere qualche relazione con il nome della variabile, dove le variabili con lo stesso nome ottenevano id lo stesso della variabile appena sostituita. Probabilmente eviti di usare id a meno che tu non abbia un buon test unitario e sia sicuro che si comporti nel modo in cui lo desideri. – ThorSummoner

risposta

114

Forse uuid.uuid4() potrebbe fare il lavoro. Vedere uuid per ulteriori informazioni.

+18

Attenzione, la libreria sottostante quel modulo è bacata e tende a biforcarsi un processo che mantiene aperti i FD. Questo è corretto nelle versioni più recenti, ma la maggior parte delle persone probabilmente non lo ha ancora, quindi in genere evito questo modulo. Mi ha causato grossi mal di testa con le prese di ascolto ... –

+2

@Glenn: Qualche altro dettaglio su quale versione è bacata? Sto usando questo nel codice di produzione (e in procinto di implementarne altri in una versione più recente). Ora sono spaventato! –

+1

@Matthew: non so se è stato corretto, ma il backend uuid che usa uuidlib ha biforcato senza chiudere FD, quindi i socket TCP che avevo aperto in quel momento non sarebbero mai stati chiusi e non potevo riaprire la porta più tardi . Dovrei uccidere manualmente 'uuidd' come root. Ho lavorato su questo impostando 'uuid._uuid_generate_time' e' uuid._uuid_generate_random' su None, quindi il modulo 'uuid' non ha mai usato l'implementazione nativa. (In realtà dovrebbe essere comunque un'opzione, la generazione di UUID casuali V4 che causano l'avvio di un demone non è necessaria.) –

-7
import time 
def new_id(): 
    time.sleep(0.000001) 
    return time.time() 

Sul mio sistema, time.time() sembra offrire 6 cifre significative dopo il punto decimale. Con un breve sonno dovrebbe essere garantito unico con almeno una moderata quantità di casualità nelle ultime due o tre cifre.

Si potrebbe hash esso pure se siete preoccupati.

+4

Hashing non lo renderà più unico, e ci sarà una forte possibilità di collisione se più di un processo lo sta facendo, ovunque, nemmeno sulla stessa macchina. Questo non è un modo per generare ID unque. –

+3

L'hashing impedirà alle persone di indovinare aumentando. Sarebbe unico se ci fosse un solo thread che distribuisse ID, credo. Molto dipende da cosa sono gli ID per _. (e perché devono essere sia unici che casuali) –

15

unico e casuale si escludono a vicenda. forse lo vuoi?

import random 
def uniqueid(): 
    seed = random.getrandbits(32) 
    while True: 
     yield seed 
     seed += 1 

Usage:

unique_sequence = uniqueid() 
id1 = next(unique_sequence) 
id2 = next(unique_sequence) 
id3 = next(unique_sequence) 
ids = list(itertools.islice(unique_sequence, 1000)) 

no due tornarono id è lo stesso (Unique) e questo si basa su un valore di seme randomizzato

+1

Questo non è unico. Se lo avvio due volte e generano un milione di valori ogni volta, le probabilità di una collisione tra le due esecuzioni sono significative. Dovrei conservare l'ultimo "seme" ogni volta per evitarlo, e quindi non ha senso avere il seme; è solo un generatore di sequenze. * Statisticamente * ID univoci tipicamente generati da dati casuali; almeno una classe di UUID funziona in questo modo. –

+1

È univoco a condizione che ogni sequenza univoca provenga da un'unica invocazione di uniqueid. non c'è garanzia di unicità tra i generatori. – SingleNegationElimination

+1

Con questa condizione, anche un contatore è unico. –

5
import time 
import random 
import socket 
import hashlib 

def guid(*args): 
    """ 
    Generates a universally unique ID. 
    Any arguments only create more randomness. 
    """ 
    t = long(time.time() * 1000) 
    r = long(random.random()*100000000000000000L) 
    try: 
     a = socket.gethostbyname(socket.gethostname()) 
    except: 
     # if we can't get a network address, just imagine one 
     a = random.random()*100000000000000000L 
    data = str(t)+' '+str(r)+' '+str(a)+' '+str(args) 
    data = hashlib.md5(data).hexdigest() 

    return data 
4

qui si possono trovare un'implementazione:

def __uniqueid__(): 
    """ 
     generate unique id with length 17 to 21. 
     ensure uniqueness even with daylight savings events (clocks adjusted one-hour backward). 

     if you generate 1 million ids per second during 100 years, you will generate 
     2*25 (approx sec per year) * 10**6 (1 million id per sec) * 100 (years) = 5 * 10**9 unique ids. 

     with 17 digits (radix 16) id, you can represent 16**17 = 295147905179352825856 ids (around 2.9 * 10**20). 
     In fact, as we need far less than that, we agree that the format used to represent id (seed + timestamp reversed) 
     do not cover all numbers that could be represented with 35 digits (radix 16). 

     if you generate 1 million id per second with this algorithm, it will increase the seed by less than 2**12 per hour 
     so if a DST occurs and backward one hour, we need to ensure to generate unique id for twice times for the same period. 
     the seed must be at least 1 to 2**13 range. if we want to ensure uniqueness for two hours (100% contingency), we need 
     a seed for 1 to 2**14 range. that's what we have with this algorithm. You have to increment seed_range_bits if you 
     move your machine by airplane to another time zone or if you have a glucky wallet and use a computer that can generate 
     more than 1 million ids per second. 

     one word about predictability : This algorithm is absolutely NOT designed to generate unpredictable unique id. 
     you can add a sha-1 or sha-256 digest step at the end of this algorithm but you will loose uniqueness and enter to collision probability world. 
     hash algorithms ensure that for same id generated here, you will have the same hash but for two differents id (a pair of ids), it is 
     possible to have the same hash with a very little probability. You would certainly take an option on a bijective function that maps 
     35 digits (or more) number to 35 digits (or more) number based on cipher block and secret key. read paper on breaking PRNG algorithms 
     in order to be convinced that problems could occur as soon as you use random library :) 

     1 million id per second ?... on a Intel(R) Core(TM)2 CPU 6400 @ 2.13GHz, you get : 

     >>> timeit.timeit(uniqueid,number=40000) 
     1.0114529132843018 

     an average of 40000 id/second 
    """ 
    mynow=datetime.now 
    sft=datetime.strftime 
    # store old datetime each time in order to check if we generate during same microsecond (glucky wallet !) 
    # or if daylight savings event occurs (when clocks are adjusted backward) [rarely detected at this level] 
    old_time=mynow() # fake init - on very speed machine it could increase your seed to seed + 1... but we have our contingency :) 
    # manage seed 
    seed_range_bits=14 # max range for seed 
    seed_max_value=2**seed_range_bits - 1 # seed could not exceed 2**nbbits - 1 
    # get random seed 
    seed=random.getrandbits(seed_range_bits) 
    current_seed=str(seed) 
    # producing new ids 
    while True: 
     # get current time 
     current_time=mynow() 
     if current_time <= old_time: 
      # previous id generated in the same microsecond or Daylight saving time event occurs (when clocks are adjusted backward) 
      seed = max(1,(seed + 1) % seed_max_value) 
      current_seed=str(seed) 
     # generate new id (concatenate seed and timestamp as numbers) 
     #newid=hex(int(''.join([sft(current_time,'%f%S%M%H%d%m%Y'),current_seed])))[2:-1] 
     newid=int(''.join([sft(current_time,'%f%S%M%H%d%m%Y'),current_seed])) 
     # save current time 
     old_time=current_time 
     # return a new id 
     yield newid 

""" you get a new id for each call of uniqueid() """ 
uniqueid=__uniqueid__().next 

import unittest 
class UniqueIdTest(unittest.TestCase): 
    def testGen(self): 
     for _ in range(3): 
      m=[uniqueid() for _ in range(10)] 
      self.assertEqual(len(m),len(set(m)),"duplicates found !") 

spero che aiuti !

+0

è davvero utile per me grazie – Virbhadrasinh

2

Forse questo lavoro per u

str(uuid.uuid4().fields[-1])[:5] 
+0

potresti elaborare sul tuo risultato str – serup

+1

Sì, capire la trasformazione e se è ancora unico sarebbe bello – alisa

+0

Come questo garantisce l'unicità? –

2

Questo funzionerà molto rapidamente, ma non genererà valori casuali, ma quelli monotonamente crescente (per un dato filo).

import threading 

_uid = threading.local() 
def genuid(): 
    if getattr(_uid, "uid", None) is None: 
     _uid.tid = threading.current_thread().ident 
     _uid.uid = 0 
    _uid.uid += 1 
    return (_uid.tid, _uid.uid) 

E 'sicuro e lavorare con le tuple può avere benefici in contrasto con le stringhe filo (più corto se non altro). Se non ti serve la sicurezza del filo, togli le punte di filettatura (invece di threading.local, usa oggetto() e rimuovi tid del tutto).

Spero che questo aiuti.