alphanumeric
alphanumeric

Reputation: 19329

How to get variable unique identification number or string

Using

a=7
print hex(id(a))

getting back:

0x7f866b425e58

Intending to use this output (converted to string) as an identification number for each class object declared I need to make sure it would stay the same while the program is running. I also need to know if a second character is always 'x' (on mac, win and linux). If I am making a bad choice choosing hex(id)) please let me know what would be a better option.

Upvotes: 0

Views: 1144

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1121844

id() is guaranteed to be stable for the lifetime of the object, but the identifier can be reused if the object is destroyed.

The 0x prefix is always going to be there when using hex(). You could also use format(..., 'x') to format to a hex number without a prefix:

>>> a = 7 
>>> print format(id(a), 'x')
7f866b425e58

You'd be better of just using a itertools.count() object to produce your unique ids, perhaps with a prefix or by negating the number if you need to distinguish these from others:

from itertools import count

id_counter = count()

and each time you need a new id, use:

next(id_counter)

and store this as an attribute on your instances. You can make the count() count down by giving it a negative step:

id_counter = count(-1, -1)

Demo:

>>> from itertools import count
>>> id_counter = count(-1, -1)
>>> next(id_counter)
-1
>>> next(id_counter)
-2

Upvotes: 7

user590028
user590028

Reputation: 11730

You might want to look at hash(obj) https://docs.python.org/2/library/functions.html#hash

Return the hash value of the object (if it has one). Hash values are integers. They are used to quickly compare dictionary keys during a dictionary lookup. Numeric values that compare equal have the same hash value (even if they are of different types, as is the case for 1 and 1.0).

Upvotes: -1

Related Questions